矩阵乘法问题 - numpy的VS Matlab的? [英] Matrix multiplication problems - Numpy vs Matlab?

查看:362
本文介绍了矩阵乘法问题 - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆