0
votes

I want to make two matrices same dimension/shape padding with zeros..

for e.g. I have

>>> x
array([[ 1.,  -1.,  1.],
       [ 1.,  1., - 1.]])
>>> 
>>> 
>>> y
array([[ 2.,  2.],
       [ 2.,  2.],
       [ -2.,  2.]])

Output I want

x1 = array([[ 1.,  -1.,  1.],
           [ 1.,  1.,  -1.],
           [ 0.,  0.,  0.]])

y1 =array([[ 2.,  2., 0.],
           [ 2.,  2., 0.],
           [ -2.,  2., 0.]])

any help? I looked up the "pad" but the numpy version we are using is older so it does not have pad. ( numpy ver. 1.6.x)

I also looked up some solutions but they are specific to shape, in my case the shape is dynamic -- and the operation needs to be fast -- as I do this over a large matrices and many times

1
How come you can't upgrade your numpy version? - YXD
I would like to ... but it affects many other projects -- otherwise I have to get special exception to go solo for my project.. and q. will be raised why cant we do it in this version? - Sendi_t
This is a common problem - you should read up on Conda environments and/or virtualenv which are designed for exactly this situation. - YXD

1 Answers

1
votes

Every array has a shape:

>>> x = np.array([[ 1.,  -1.,  1.],
...               [ 1.,  1., - 1.]])
>>> y = np.array([[ 2.,  2.],
...               [ 2.,  2.],
...               [ -2.,  2.]])
>>> x.shape
(2, 3)
>>> y.shape
(3, 2)

We just need to compute the "maximum shape" and use that for the new arrays:

>>> shape = np.maximum(x.shape, y.shape)
>>> x1 = np.zeros(shape)

We can then copy the data from the original arrays into the corresponding parts of the new arrays:

>>> x1[:x.shape[0], :x.shape[1]] = x
>>> y1 = np.zeros(shape)
>>> y1[:y.shape[0], :y.shape[1]] = y

Results

>>> x1
array([[ 1., -1.,  1.],
       [ 1.,  1., -1.],
       [ 0.,  0.,  0.]])
>>> y1
array([[ 2.,  2.,  0.],
       [ 2.,  2.,  0.],
       [-2.,  2.,  0.]])
>>>