简体   繁体   中英

Matrix multiplication problems - Numpy vs Matlab?

I am trying to translate some Matlab code I have into Python (using numpy). I have the following Matlab code:

(1/x)*eye(2)

X is simply 1000000. As I understand, * in Matlab indicates matrix multiplication, and the equivalent is .dot in numpy. So in Python, I have:

numpy.array([(1/x)]).dot(numpy.identity(2))

I get the error "shapes (1,) and (2,2) not aligned: 1 (dim 0) != 2 (dim 0)" when I try to run the numpy code.

Apparently I'm not understanding something. Anybody know what the proper numpy code would be?

Since x is a scalar, if you multiply a matrix by a scalar in MATLAB it simply scales all of the entries by that value. There is no need for matrix multiplication.

If you want to achieve the same thing in numpy , you do the same operation as in MATLAB:

(1/x)*numpy.identity(2)

If x is a matrix of compatible dimensions, then yes you use numpy.dot :

(1/x).dot(numpy.identity(2))

As such, you need to make sure that you know what x is before you decide to do the operation.

numpy performs element-wise multiplication by using the * operator and so if you want actual matrix multiplication, yes use numpy.dot . You are getting incompatible dimensions because true matrix multiplication between a scalar and matrix is not possible.

Basically in numpy operations * and dot are different.

(*) performs element wise operation – each matrix element with other matrix corresponding element

a.dot(c) – performs actual mathematical matrix multiplication, which we studied in our highschool.

a = np.arange(9).reshape(3,3)

b = np.arange(10,19).reshape(3,3)

In [47]: a*b

Out[47]:
array([[ 0, 11, 24],
[ 39, 56, 75],
[ 96, 119, 144]])

In [48]: a.dot(b)

Out[48]:
array([[ 45, 48, 51],
[162, 174, 186],
[279, 300, 321]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM