# How to sum / add two or several matrices together in python ?

Published: November 20, 2019

Examples of how to sum / add two or several matrices together in python using numpy:

### Add two matrices of same size

Let sum two matrices of same size. Let's consider the matrix A:

>>> import numpy as np
>>> A = np.array(([3,1],[6,4]))
>>> A
array([[3, 1],
       [6, 4]])


A = \left( \begin{array}{ccc}
3 & 1 \\
6 & 4
\end{array}\right)

and matrix B:

>>> B = np.array(([1,8],[4,2]))
>>> B
array([[1, 8],
       [4, 2]])


B = \left( \begin{array}{ccc}
1 & 8 \\
4 & 2
\end{array}\right)

Those two matrices have the same size:

>>> A.shape
(2, 2)
>>> B.shape
(2, 2)
>>> A.shape == B.shape
True


Then to sum A and B, a solution is to use the operator +

>>> R = A + B
>>> R
array([[ 4,  9],
       [10,  6]])
>>>


R = A + B =
\left( \begin{array}{ccc}
3 & 1 \\
6 & 4
\end{array}\right)
+ \left( \begin{array}{ccc}
1 & 8 \\
4 & 2
\end{array}\right)
=
\left( \begin{array}{ccc}
4 & 9 \\
10 & 6
\end{array}\right)

The operator + can be used to add multiple matrices:

>>> A = np.array(([1,2],[3,4]))
>>> B = np.array(([2,2],[2,2]))
>>> C = np.array(([10,10],[10,10]))
>>> R = A + B + C
>>> R
array([[13, 14],
       [15, 16]])


R = A + B + C =
\left( \begin{array}{ccc}
1 & 2 \\
3 & 4
\end{array}\right)
+ \left( \begin{array}{ccc}
2 & 2 \\
2 & 2
\end{array}\right)
+
\left( \begin{array}{ccc}
10 & 10 \\
10 & 10
\end{array}\right)
=
\left( \begin{array}{ccc}
13 & 14 \\
15 & 16
\end{array}\right)

### Add two matrices of different size

If the matrices have not the same size

>>> A = np.array(([1,2,3],[4,5,6],[7,8,9]))
>>> A
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> B = np.array(([10,20],[30,40]))
>>> B
array([[10, 20],
       [30, 40]])


the operator + do not work (except if one matrix has only 1 element see next section))

>>> A + B
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (3,3) (2,2)


but it is possible to slice a matrix

>>> A[0:2,0:2]+B
array([[11, 22],
       [34, 45]])


Another example

>>> A[1:3,0:2]+B
array([[14, 25],
       [37, 48]])


### Add a number to each element of a matrix

To add a number to each element of a matrix, the operator + is still working:

>>> A = np.array(([3,1],[6,4]))
>>> A
array([[3, 1],
       [6, 4]])
>>> R = A + 100
>>> R
array([[103, 101],
       [106, 104]])
>>>


Another example

>>> A = np.array(([3,1],[6,4]))
>>> B = np.array(([100]))
>>> A + B
array([[103, 101],
       [106, 104]])


### Concatenate two matrices

Note: to concatenate two matrices, a solution is to use the function concatenate:

>>> A = np.array(([3,1],[6,4]))
>>> A
array([[3, 1],
       [6, 4]])
>>> B = np.array(([1,8],[4,2]))
>>> B
array([[1, 8],
       [4, 2]])
>>> np.concatenate((A,B),axis=0)
array([[3, 1],
       [6, 4],
       [1, 8],
       [4, 2]])
>>> np.concatenate((A,B),axis=1)
array([[3, 1, 1, 8],
       [6, 4, 4, 2]])