0

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

3
  • How come you can't upgrade your numpy version? Commented May 26, 2015 at 16:06
  • 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? Commented May 26, 2015 at 16:16
  • This is a common problem - you should read up on Conda environments and/or virtualenv which are designed for exactly this situation. Commented May 26, 2015 at 16:21

1 Answer 1

1

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.]]) >>> 
Sign up to request clarification or add additional context in comments.

6 Comments

golden! , just quick q. here we are creating an empty array of zeros for x1, y1 of maximum shape, and than updating it --- I have matrix of 2k x 1k ( approximately ) since rows and column varies a little bit.. That means I will be holding 4 matrix at a time in memory.. do you think it will light enough? or should I loop?
I doubt you will run out of memory as each of those arrays will be ~16MB. Also the code y1[:y.shape[0], :y.shape[1]] = y will also just copy data into the previously allocated/zeroed memory rather than reallocating memory.
Thanks! ~16MB ? as they are all (same) zeros (floats), wouldn't it optimize memory space? and only updated matrix will be actual size? is there any other lib that can do that?
This is basically what pad does, but with more options - create the destination array of the correct size, and copy old onto the new.
Thank you hpaulj -- I need to create habit of looking into python/lib implementations.. :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.