# How to upsample an array (matrix) by repeating elements using numpy in python ?

Published: November 18, 2020

Tags: Python; Numpy;

An example of how to upsample an array by repeating elements using numpy in python

### Upsample an array using numpy function kron

Lets consider the following matrix of initial shape (2,2):

import numpy as np

a = np.array([[0,1], [2,3]])

print(a)
print(a.shape)


\left( \begin{array}{ccc}
0 &1 \\
2 & 3
\end{array}\right)

to upsample a matrix, a solution is to use the numpy function kron (which compute the Kronecker product):

a_upsampled = np.kron(a, np.ones((2,2)))

print(a_upsampled)
print(a_upsampled.shape)


returns

\left( \begin{array}{ccc}
0 & 0 & 1 & 1 \\
0 & 0 & 1 & 1 \\
2 & 2 & 3 & 3 \\
2 & 2 & 3 & 3
\end{array}\right)

of shape (4, 4) (since (2,2)*(2,2) = (4,4)). Another example using np.ones((2,4) to compute the Kronecker product:

a_upsampled = np.kron(a, np.ones((2,4)))

print(a_upsampled)
print(a_upsampled.shape)


returns

\left( \begin{array}{ccc}
0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 \\
0 & 0 & 0 & 0 & 1 & 1 & 1 & 1 \\
2 & 2 & 2 & 2 & 3 & 3 & 3 & 3 \\
2 & 2 & 2 & 2 & 3 & 3 & 3 & 3
\end{array}\right)

of shape (4, 8) (since (2,2)*(2,4) = (4,8)).

### Upsample an array using numpy function repeat

Another option is to use the numpy function repeat, for example:

a.repeat(2, axis=0).repeat(2, axis=1)


returns

\left( \begin{array}{ccc}
0 & 0 & 1 & 1 \\
0 & 0 & 1 & 1 \\
2 & 2 & 3 & 3 \\
2 & 2 & 3 & 3
\end{array}\right)

of shape (4, 4).