2

Assuming I have 3 numpy square matrices of various shapes:

AxA
BxB
CxC

Is there a numpy function which would expand the matrices to the maximum size and put some default values in new cells? Example:

3x3
5x5
10x10

should result in 3 10x10 arrays.

Mark
  • 6,052
  • 8
  • 61
  • 129
  • Does this answer your question? [Good ways to "expand" a numpy ndarray?](https://stackoverflow.com/questions/12668027/good-ways-to-expand-a-numpy-ndarray) – AMC Jan 18 '20 at 01:53
  • @AMC, thanks for sharing the link. It's not exactly fitting my demands, but has useful information! – Mark Jan 19 '20 at 23:49

1 Answers1

3

As long as you want the original values of a and b to be stored in the "upper left", you could go with initializing a new array with your wanted fill_value (say, 99) and place your smaller arrays in it like this:

import numpy as np

a = np.ones(shape=(3,3))
b = np.ones(shape=(5,5))
c = np.ones(shape=(10,10))

a2 = np.full(shape=(10,10), fill_value=99)
a2[:a.shape[0], :a.shape[1]] = a

b2 = np.full(shape=(10,10), fill_value=99)
b2[:b.shape[0], :b.shape[1]] = b

##

>> a2:
[[ 1  1  1 99 99 99 99 99 99 99]
 [ 1  1  1 99 99 99 99 99 99 99]
 [ 1  1  1 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]]

Edit:

If you want to do this automatically, without having to know the dimension of the largest square array:

a = np.ones(shape=(3,3))
b = np.ones(shape=(5,5))
c = np.ones(shape=(10,10))

list_of_arrays = [a, b, c]
shapes = [arr.shape for arr in list_of_arrays]
max_shape = max(shapes)

for iarr, arr in enumerate(list_of_arrays):
    arr_new = np.full(shape=max_shape, fill_value=99)
    arr_new[:arr.shape[0], :arr.shape[1]] = arr
    list_of_arrays[iarr] = arr_new


>> print(list_of_arrays[1])
[[ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [ 1  1  1  1  1 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]
 [99 99 99 99 99 99 99 99 99 99]]
offeltoffel
  • 2,691
  • 2
  • 21
  • 35