averaging elements in a matrix with the corresponding elements in another matrix (in python)

Question:

I have the following matrices:

1  2  3

4  5  6

7  8  9

m2:

2  3  4

5  6  7

8  9  10

I want to average the two to get:

1.5  2.5  3.5

4.5  5.5  6.5

7.5  8.5  9.5

What is the best way of doing this?

Thanks

Asked By: cwei

||

Answers:

List comprehensions and the zip function are your friends:

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

Of course, the numpy package makes these kind of computations trivially easy:

>>> 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]])
Answered By: Raymond Hettinger

The obvious answer would be:

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

Perhaps a more elegant way (although probably a bit slower) to do it would be to use the numpy.mean function on a stacked version of the two arrays:

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]])
Answered By: talonmies
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.