Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy transpose multiplication problem

I tried to find the eigenvalues of a matrix multiplied by its transpose but I couldn't do it using numpy.

testmatrix = numpy.array([[1,2],[3,4],[5,6],[7,8]])
prod = testmatrix * testmatrix.T
print eig(prod)

I expected to get the following result for the product:

5    11    17    23
11    25    39    53
17    39    61    83
23    53    83   113

and eigenvalues:

0.0000
0.0000
0.3929
203.6071

Instead I got ValueError: shape mismatch: objects cannot be broadcast to a single shape when multiplying testmatrix with its transpose.

This works (the multiplication, not the code) in MatLab but I need to use it in a python application.

Can someone tell me what I'm doing wrong?

like image 574
Virgiliu Avatar asked Jul 09 '10 13:07

Virgiliu


People also ask

What is difference between .T and transpose () in NumPy?

T and the transpose() call both return the transpose of the array. In fact, . T return the transpose of the array, while transpose is a more general method_ that can be given axes ( transpose(*axes) , with defaults that make the call transpose() equivalent to . T ).

How does transpose work in NumPy?

NumPy Matrix transpose() - Transpose of an Array in PythonThe transpose of a matrix is obtained by moving the rows data to the column and columns data to the rows. If we have an array of shape (X, Y) then the transpose of the array will have the shape (Y, X).

Is Matmul faster than dot?

matmul and both outperform np. dot . Also note, as explained in the docs, np.

Is NumPy matrix multiplication faster?

Faster libraries: Numpy As an example, let's compute matrix powers. Specifically, we compute A16 where A is a 100×100 matrix. Our plain Python solution takes 11.77 seconds to run, while using Numpy to perform the multiplications and generate the matrices takes 0.0097 seconds to run.


2 Answers

You might find this tutorial useful since you know MATLAB.

Also, try multiplying testmatrix with the dot() function, i.e. numpy.dot(testmatrix,testmatrix.T)

Apparently numpy.dot is used between arrays for matrix multiplication! The * operator is for element-wise multiplication (.* in MATLAB).

like image 138
Jacob Avatar answered Oct 24 '22 00:10

Jacob


You're using element-wise multiplication - the * operator on two Numpy matrices is equivalent to the .* operator in Matlab. Use

prod = numpy.dot(testmatrix, testmatrix.T)
like image 8
ptomato Avatar answered Oct 24 '22 00:10

ptomato