Matrix multiplication problems - Numpy vs Matlab?

天大地大妈咪最大 提交于 2020-01-11 12:27:07

问题


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?


回答1:


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.




回答2:


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]])


来源:https://stackoverflow.com/questions/30577114/matrix-multiplication-problems-numpy-vs-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!