matlab数组乘法到python

时间:2014-01-17 06:44:21

标签: python matlab numpy

我有2个numpy数组

[a] = [[1] [2] [3]]
[b] = [[4] [5] [6]]

我想将matlab行转换为python

A = a*b';

我将如何在python中执行此操作以及在matlab中表示什么?

2 个答案:

答案 0 :(得分:3)

使用numpy.dot

In [7]: a=np.array([1,2,3])

In [8]: b=np.array([4,5,6,])

In [9]: a.dot(b)
Out[9]: 32

如果您希望结果仍然是矩阵,请使用numpy.matrix

In [239]: ma=matrix([1,2,3])

In [240]: ma
Out[240]: matrix([[1, 2, 3]])

In [241]: mb=matrix([4,5,6])

In [242]: mb.T
Out[242]: 
matrix([[4],
        [5],
        [6]])

In [243]: ma*mb.T
Out[243]: matrix([[32]])

<强>更新

如果您的阵列是打印a.shape时形状为(m,n)的2D阵列,则应使用.T转置第二个阵列,否则会得到ValueError: objects are not aligned

In [30]: a
Out[30]: array([[1, 2, 3]])
In [31]: b
Out[31]: array([[4, 5, 6]])
In [32]: a.dot(b.T)
Out[32]: array([[32]])
In [33]: a.dot(b)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-9a1f5761fa9d> in <module>()
----> 1 a.dot(b)
ValueError: objects are not aligned

答案 1 :(得分:1)

你需要transpose第一个数组:

import numpy as np
a = np.array([[1], [2], [3]])
b = np.array([[4], [5], [6]])
np.dot(a.T, b)

或第二个数组:

np.dot(a, b.T)