# Props to numpy programmers!

Discussion in 'Python' started by Andrew Felch, Nov 20, 2003.

1. ### Andrew FelchGuest

So I wanted to matrixmultiply

[[a,b],
[c,d]]

*

[e,f]

Of course this is impossible, because the number of columns in the
first factor is not equal to the number of rows in the second. Wrong!
It is impossible because the second matrix is rank1! So numpy
happily converts it to a column vector so the multiplication will
work, and converts the answer back into a rank1 vector!!!!

I love NUMPY!!!!!!!!!!!

I was reading my code and thought I had a bug, I couldn't figure out
why the code was still working right! It's because the numpy people
are geniouses!

Hooray numpy!!!!!!!!!! Numpy is smarter than me!

Andrew Felch, Nov 20, 2003

2. ### Duncan SmithGuest

"Andrew Felch" <> wrote in message
news:...
> So I wanted to matrixmultiply
>
> [[a,b],
> [c,d]]
>
> *
>
> [e,f]
>
> Of course this is impossible, because the number of columns in the
> first factor is not equal to the number of rows in the second. Wrong!
> It is impossible because the second matrix is rank1! So numpy
> happily converts it to a column vector so the multiplication will
> work, and converts the answer back into a rank1 vector!!!!
>
> I love NUMPY!!!!!!!!!!!
>
> I was reading my code and thought I had a bug, I couldn't figure out
> why the code was still working right! It's because the numpy people
> are geniouses!
>
> Hooray numpy!!!!!!!!!! Numpy is smarter than me!

I love Numpy too. But I wouldn't want this multiplication to work if the
second array was a row vector (and there's no explicit distinction because
of the array's shape).

>>> a

array([[0, 1],
[2, 3]])
>>> b

array([4, 5])
>>> Numeric.matrixmultiply(a,b)

array([ 5, 23])
>>> Numeric.matrixmultiply(b,a)

array([10, 19])

One of these multiplications should fail, depending on whether b is a column
or row vector.

Make it a column vector by reshaping,

>>> b = Numeric.reshape(b, (2,1))
>>> b

array([[4],
[5]])

and it does the right thing.

>>> Numeric.matrixmultiply(a,b)

array([[ 5],
[23]])
>>> Numeric.matrixmultiply(b,a)

Traceback (most recent call last):
File "<pyshell#60>", line 1, in -toplevel-
Numeric.matrixmultiply(b,a)
File "C:\Python23\lib\site-packages\Numeric\Numeric.py", line 335, in dot
return multiarray.matrixproduct(a, b)
ValueError: matrices are not aligned
>>>

Much safer IMHO.

Duncan

Duncan Smith, Nov 20, 2003