Python how to add two maticies with different number of rows and columns?

Viewed 27

Suppose I have two 2D matricies: [[1,2],[0,0]] and [[4,8],[0,0],[5,6]] and I want to sum them up and get the matrix [[5,10],[0,0],[5,6]]. How can I do it in the most easiest way without writing my own function? As I understood, numpy matricies don't support this.

import numpy as np
m1 = np.array([[1, 2], [0, 0]])
m2 = np.array([[4, 8], [0, 0], [5, 6]])
res = m1+m2 
1 Answers
import numpy as np

m1 = np.array([[1, 2], [0, 0]])
m2 = np.array([[4, 8], [0, 0], [5, 6]])

# Array size matching
m1.resize(m2.shape) if m1.shape < m2.shape else m2.resize(m1.shape)

answer = m1 + m2
print(answer)

Output:

[[ 5 10]
 [ 0  0]
 [ 5  6]]
Related