Newbie question

Robert Kern robert.kern at gmail.com
Thu Nov 6 17:08:22 EST 2008


Joe Hays wrote:
> I'm a newbie to python. Can anyone tell me why the following little 
> program complains about incorrect dimensions?
> 
> <snip>
> 
>     import pylab
>     from pylab import *
> 
>     n = 10; m = 2*n;
>     A = randn(m,n);
>     b = A*rand(n,1) + 2*rand(m,1);
> 
> </snip>
> 
> The actual error I receive is,
> 
> <snip>
> 
>     b = A*rand(n,1) + 2*rand(m,1);
>     ValueError: shape mismatch: objects cannot be broadcast to a single
>     shape
> 
> </snip>
> 
> This is supposed to be doing a matrix multply of an (m,n)(n,1). This 
> results in an (m,1). This should then be able to be added to the 
> 2*rand(m,1), but, its not for some reason.
> 
> Ideas?

You will want to ask numpy questions on the numpy mailing list (preferably with 
a subject line a bit more informative with respect to the actual problem).

   http://www.scipy.org/Mailing_Lists

In this case, the problem is that * does not do matrix multiplication; it does 
element-wise multiplication. Use dot(A, randn(n,1)) instead.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list