0

I have a numpy array A with shape (M,N). I want to create a new array B with shape (M,N,3) where the result would be the same as the following:

import numpy as np

def myfunc(A,sx=1.5,sy=3.5):
    M,N=A.shape
    B=np.zeros((M,N,3))

    for i in range(M):
        for j in range(N):
            B[i,j,0]=i*sx
            B[i,j,1]=j*sy
            B[i,j,2]=A[i,j]
    return B

A=np.array([[1,2,3],[9,8,7]])
print(myfunc(A))

Giving the result:

[[[0.  0.  1. ]
  [0.  3.5 2. ]
  [0.  7.  3. ]]

 [[1.5 0.  9. ]
  [1.5 3.5 8. ]
  [1.5 7.  7. ]]]

Is there a way to do it without the loop? I was thinking whether numpy would be able to apply a function element-wise using the indexes of the array. Something like:

def myfuncEW(indx,value,out,vars):
    out[0]=indx[0]*vars[0]
    out[1]=indx[1]*vars[1]
    out[2]=value

M,N=A.shape
B=np.zeros((M,N,3))
np.applyfunctionelementwise(myfuncEW,A,B,(sx,sy))

3 Answers 3

0

You could use mgrid and moveaxis:

>>> M, N = A.shape
>>> I, J = np.mgrid[:M, :N] * np.array((sx, sy))[:, None, None]
>>> np.moveaxis((I, J, A), 0, -1)
array([[[ 0. ,  0. ,  1. ],
        [ 0. ,  3.5,  2. ],
        [ 0. ,  7. ,  3. ]],

       [[ 1.5,  0. ,  9. ],
        [ 1.5,  3.5,  8. ],
        [ 1.5,  7. ,  7. ]]])
>>> 
Sign up to request clarification or add additional context in comments.

Comments

0

You could use meshgrid and dstack, like this:

import numpy as np

def myfunc(A,sx=1.5,sy=3.5):
    M, N = A.shape
    J, I = np.meshgrid(range(N), range(M))
    return np.dstack((I*sx, J*sy, A))

A=np.array([[1,2,3],[9,8,7]])
print(myfunc(A))

# array([[[ 0. ,  0. ,  1. ],
#         [ 0. ,  3.5,  2. ],
#         [ 0. ,  7. ,  3. ]],
#
#        [[ 1.5,  0. ,  9. ],
#         [ 1.5,  3.5,  8. ],
#         [ 1.5,  7. ,  7. ]]])

Comments

0

By preallocating the 3d array B, you save about half the time compared to stacking I, J and A.

def myfunc(A, sx=1.5, sy=3.5):
    M, N = A.shape
    B = np.zeros((M, N, 3))
    B[:, :, 0] = np.arange(M)[:, None]*sx
    B[:, :, 1] = np.arange(N)[None, :]*sy
    B[:, :, 2] = A
    return B

Comments

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.