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

Pearu Peterson pearu at cens.ioc.ee
Wed Mar 6 12:00:31 CST 2002

On Wed, 6 Mar 2002, Perry Greenfield wrote:

> Other suggestions?

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.

  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?


More information about the Numpy-discussion mailing list