平均矩阵中的元素与另一个矩阵中的对应元素(在python中)

时间:2012-03-25 07:04:06

标签: python matplotlib

我有以下矩阵:

1  2  3

4  5  6

7  8  9

m2:

2  3  4

5  6  7

8  9  10

我想平均得到两个:

1.5  2.5  3.5

4.5  5.5  6.5

7.5  8.5  9.5

这样做的最佳方式是什么?

由于

2 个答案:

答案 0 :(得分:3)

List comprehensionszip功能是您的朋友:

>>> from __future__ import division
>>> m1 = [[1,2,3], [4,5,6], [7,8,9]]
>>> m2 = [[2,3,4], [5,6,7], [8,9,10]]
>>> [[(x+y)/2 for x,y in zip(r1, r2)] for r1, r2 in zip(m1, m2)]
[[1.5, 2.5, 3.5], [4.5, 5.5, 6.5], [7.5, 8.5, 9.5]]

当然,numpy包使得这些计算变得非常简单:

>>> from numpy import array
>>> m1 = array([[1,2,3], [4,5,6], [7,8,9]])
>>> m2 = array([[2,3,4], [5,6,7], [8,9,10]])
>>> (m1 + m2) / 2
array([[ 1.5,  2.5,  3.5],
       [ 4.5,  5.5,  6.5],
       [ 7.5,  8.5,  9.5]])

答案 1 :(得分:0)

显而易见的答案是:

m1 = np.arange(1,10,dtype=np.double).reshape((3,3))
m2 = 1. + m1
m_average = 0.5 * (m1 + m2)
print m_average

array([[ 1.5,  2.5,  3.5],
       [ 4.5,  5.5,  6.5],
       [ 7.5,  8.5,  9.5]])

也许更优雅的方式(尽管可能有点慢)可以在两个数组的堆叠版本上使用numpy.mean函数:

m_average = np.dstack([m1,m2]).mean(axis=2)
print m_average

array([[ 1.5,  2.5,  3.5],
       [ 4.5,  5.5,  6.5],
       [ 7.5,  8.5,  9.5]])