3

I have a matrix

a = [[11 12 13 14 15]
     [21 22 23 24 25]
     [31 32 33 34 35]
     [41 42 43 44 45]
     [51 52 53 54 55]]

I would sample it in such a way

b = a[::2,::3]
b >> [[11 14]
      [31 34]
      [51 54]]

Now only using b (assume 'a' never existed, I just know the shape) how do I get the following output

x = [[11 0  0 14 0]
    [0  0  0  0 0]
    [31 0  0 34 0]
    [0  0  0  0 0]
    [51 0  0 54 0]]
2
  • Do check out @B. M.'s solution. Might be a better fit. Commented Nov 21, 2017 at 19:55
  • 1
    Yes, But I just modified your solution, as I know the Shape of A, but this "out[::row_step,::col_step] = b" was something new to me. I never thought of it that way Commented Nov 21, 2017 at 20:07

2 Answers 2

5

Using array-intialization -

def retrieve(b, row_step, col_step):
    m,n = b.shape
    M,N = max(m,row_step*m-1), max(n,col_step*n-1)
    out = np.zeros((M,N),dtype=b.dtype)
    out[::row_step,::col_step] = b
    return out

Sample runs -

In [150]: b
Out[150]: 
array([[11, 14],
       [31, 34],
       [51, 54]])

In [151]: retrieve(b, row_step=2, col_step=3)
Out[151]: 
array([[11,  0,  0, 14,  0],
       [ 0,  0,  0,  0,  0],
       [31,  0,  0, 34,  0],
       [ 0,  0,  0,  0,  0],
       [51,  0,  0, 54,  0]])

In [152]: retrieve(b, row_step=3, col_step=4)
Out[152]: 
array([[11,  0,  0,  0, 14,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [31,  0,  0,  0, 34,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0],
       [51,  0,  0,  0, 54,  0,  0],
       [ 0,  0,  0,  0,  0,  0,  0]])

In [195]: retrieve(b, row_step=1, col_step=3)
Out[195]: 
array([[11,  0,  0, 14,  0],
       [31,  0,  0, 34,  0],
       [51,  0,  0, 54,  0]])
Sign up to request clarification or add additional context in comments.

Comments

3

knowing a.shape, an other solution is :

def fill (b,shape):
    a=np.zeros(shape,dtype=b.dtype)
    x = a.shape[0]//b.shape[0]+1
    y = a.shape[1]//b.shape[1]+1
    a[::x,::y]=b
    return a

Try :

In [247]: fill(b,a.shape)
Out[247]: 
array([[11,  0,  0, 14,  0],
       [ 0,  0,  0,  0,  0],
       [31,  0,  0, 34,  0],
       [ 0,  0,  0,  0,  0],
       [51,  0,  0, 54,  0]])

1 Comment

Yup, this seems like a better version given the array shape.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.