# [Numpy-discussion] adding a .M attribute to the array.

Perry Greenfield perry at stsci.edu
Wed Mar 6 12:43:59 CST 2002

```Pearu writes:

>
> Here is one suggestion that is based on the observation that all we need
> is an easy way to tell that the following operation should be applied
> as a matrix operation. So, the suggestion is to provide an attribute or a
> member function that returns an array (note, not a Matrix instance) that
> has a bit, called it asmatrix, set true but _only_ temporally. The bit is
> cleaned on every operation. And before applying an operation, the
> corresponding method (currently there seem to be only four relevant
> methods: __mul__, __pow__ and their r-versions) checks if either of
> the operants has asmatrix bit true, then performs the corresponding matrix
> operation, otherwise the default element-wise operation. And before
> returning, it cleans up asmatrix bit.
>
> For the sake of an example, let .m be Numeric array attribute that when
> accessed sets asmatrix=1 and returns the array.
> Examples:
>
>   a * b       - is element-wise multiplication
>   a.m * b, a * b.m   - are matrix multiplications, the resulting
>                        array, as well a and b, have asmatrix=0
>   a.m ** -1   - is matrix inverse
>   sin(a)      - element-wise sin
>   sin(a.m)    - matrix sin
>
> To summarize the main ideas:
>  * array has asmatrix bit that most of the time is false.
>  * there is a way to set the asmatrix bit true, either by .m or .M
>    attributes or .m(), .M(), .. methods that return the same array.
>  * __mul__, __pow__, etc. methods check if either operant has asmatrix
>    true, then performs the corresponding matrix operation, otherwise
>    the corresponding element-wise operation.
>  * all operations clean asmatrix bit.
>
> So, what do you think?
>
> 	Pearu
>
This is a clever idea that reminds me of  something we were considering
for something else (exactly what I can't quite remember :-). But like
all such schemes it still does produce an object, and a user might
infer (reasonably or unreasonably) that if they can type

x = a.m * b

Then they can treat a.m as an array, e.g.,

x = a.m

In that case, the special case behavior still becomes camouflaged,
when x is used later, albeit only to bite you once. It is clear
what the operation does when the attribute is used in the expression,
but if it isn't, there is still room for confusion. I like the
idea, but I'll have to think about whether the downside outweighs
the benefits.

Perry

```