[SciPy-User] A newbie question on matrix multiplication

Paul Anton Letnes paul.anton.letnes@gmail....
Thu Mar 25 10:16:13 CDT 2010


Hi.

On 25. mars 2010, at 06.29, Graziano Mirata wrote:

> 	Hi to everybody, 
> i am new here and above all I am new in python. After years of matlab programming I finally have switched to Python. 
> 
> Coming to question: i am trying to multiply a matrix transpose by itself but i've got an error on the shape. But it is impossible. Here there is the code: 
> 
> type(f) 
> Out[213]: <type 'numpy.ndarray'> 
> 
In numpy, you have 2 distinct classes representing arrays and matrices. In general, arrays are n-dimensional and use element-wise multiplication. Matrices are 2-dimensional and use matrix multiplication, matlab-style.
>>> import numpy
>>> a = numpy.eye(3)
>>> type(a)
<type 'numpy.ndarray'>
>>> a = numpy.mat(a)
>>> type(a)
<class 'numpy.matrixlib.defmatrix.matrix'>

So take your arrays and put them inside a numpy.mat() function call, and you're basically back to matlab-style matrices. Be careful which type you have - as in matlab, it matters a lot whether you are doing matrix or element-wise multiplication...

-Paul



> In [214]: type(ft) 
> Out[214]: <type 'numpy.ndarray'> 
> 
> In [215]: f.size 
> Out[215]: 12 
> 
> In [216]: f.shape 
> Out[216]: (4, 3) 
> 
> In [217]: ft = f.transpose() 
> 
> In [218]: ft.shape 
> Out[218]: (3, 4) 
> 
> In [219]: ft*f 
> --------------------------------------------------------------------------- 
> ValueError                                Traceback (most recent call last) 
> 
> /Users/Graz/Documents/PhD researchs/Outsample Perf KT/PythonCodesOSPKT/<ipython console> in <module>() 
> 
> ValueError: shape mismatch: objects cannot be broadcast to a single shape 
> 
> 
> Any idea where i am wrong? 
> 
> Thanx 
> 
> G 
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user



More information about the SciPy-User mailing list