矩阵乘法问题 - numpy的VS Matlab的? [英] Matrix multiplication problems - Numpy vs Matlab?
问题描述
我想翻译一些Matlab的code我到Python(使用numpy的)。我有以下Matlab的code:
(1 / X)*眼(2)
x仅仅是1000000。据我了解,*在Matlab表示矩阵乘法,和等效于numpy的.DOT。因此,在Python中,我有:
numpy.array([(1 / X)])。点(numpy.identity(2))
我得到的错误形状(1)和(2,2)未对齐:1(0变暗)= 2(0变暗)!当我尝试运行numpy的code
显然,我不理解的东西。任何人都知道正确的numpy的code会是什么?
由于 X
是标量,如果你在MATLAB标量乘以矩阵它只是缩放所有由该值的条目。没有必要为矩阵乘法
如果你想实现在 numpy的
同样的事情,你做同样的操作在MATLAB:
(1 / X)* numpy.identity(2)
如果 X
兼容维度的矩阵,然后是你使用 numpy.dot
:
(1 / X).DOT(numpy.identity(2))
因此,你需要确保你知道什么 X
是你决定做操作之前。
numpy的
使用 *
经营者和执行逐元素相乘,所以如果你想实际的矩阵乘法,是使用 numpy.dot
。你得到不兼容的尺寸,因为一个标量与基体之间真正的矩阵乘法是不可能的。
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.
这篇关于矩阵乘法问题 - numpy的VS Matlab的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!