[Numpy-discussion] Should dot return 1x1 matrix as scalar?

Travis Oliphant oliphant at ee.byu.edu
Fri Jan 13 09:07:02 CST 2006

Paulo J. S. Silva wrote:

>Ops... You are right. The example is not good. Look this though (now I
>am actually copying my ipython session, instead of "remembering" it):
>--- Session copy here ---
>In [5]:x = matrix(arange(10.)).T
>In [6]:x = matrix(arange(3.)).T
>In [7]:A = matrix([[1.,2,3],[4,5,6],[7,8,9]])
>In [8]:b = x.T*x*A
>exceptions.ValueError                                Traceback (most
>recent call last)
>/usr/local/lib/python2.4/site-packages/numpy/core/defmatrix.py in
>__mul__(self, other)
>    126             return N.multiply(self, other)
>    127         else:
>--> 128             return N.dot(self, other)
>    129
>    130     def __rmul__(self, other):
>ValueError: matrices are not aligned
>--- End of copy ---
>You see, the inner product can not be used to mutiply by a matrix, which
>is very odd in linear algebra. As the matrix class is supposed to
>represent the linear algebra object we I see two options:
>1) Change the __mul__, __rmul__, __imul__ to deal with 1x1 matrices as
>2) Change dot to convert 1x1 matrix to scalar at return.


3)  Return scalars instead of 1x1 matrices inside of __array_finalize__ 
(where the magic of ensuring matrices are rank-2 arrays is actually done).

More information about the Numpy-discussion mailing list