user9187374
user9187374

Reputation: 309

sum of two matrix row by column

I have two matrix:

mx1 = np.matrix([[2,9,9],[2,5,8],[7,2,9]])

[[2 9 9]
 [2 5 8]
 [7 2 9]]

mx2 = np.matrix([[7,1,3],[5,8,2],[6,9,5]])

[[7 1 3]
 [5 8 2]
 [6 9 5]]

I would like to do something like the matrix product row by column but with sum.

i.e., the resulting matrix element[1,1] should be calculated as:

(2+7)+(9+5)+(9+6) = 38

element[1,2]:

(2+1)+(9+8)+(9+9) = 38

and so on.

Some smart way to do so?

Upvotes: 0

Views: 390

Answers (3)

Aguy
Aguy

Reputation: 8059

I think this will do what you want, but I'm not sure how efficient it is and will it work well for your large data.

import itertools

m, _ = np.shape(mx1)
_, n = np.shape(mx2)

r = np.array(list(map(np.sum, itertools.product(mx1, mx2.T)))).reshape(m, n)

To break this down: use itertools.product to create all pairs of row and column. Sum these pairs. Then reshape according to the original shapes. I hope this will be useful.

Upvotes: 0

Mr. T
Mr. T

Reputation: 12410

How about using numpy broadcasting?

mx1 = np.matrix([[2,9,9],[2,5,8],[7,2,9]])
mx2 = np.matrix([[7,1,3],[5,8,2],[6,9,5]])
res = np.sum(mx1, axis = 1) + np.sum(mx2, axis = 0)

Upvotes: 5

Pam
Pam

Reputation: 1163

numpy transpose your second matrix and then do an element wise addition.

mx2t = np.transpose(mx2)
motot = np.add(mx1, mx2t)

Then use numpy with an axis argument to sum the columns. (I assume for your example, you will end up with a 1x3 matrix, not a 3x3 matrix as I'm not clear how you would calculate element[2,2]).

Upvotes: 0

Related Questions