1

I have two 2D numpy arrays a(N,D) b(M,D) and I want to fill a third array c(M,D*N) which is a function of a and b. If N= 2 and D=3 I want c to be the following:

c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]    
c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2] 

c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1] 
c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2] 

How can I fill c using a loop (for, while)?

3
  • Why not use vectorized tools? When working with arrays, you might prefer the efficiency? Commented May 31, 2019 at 9:15
  • what do you mean by vectorized tools? Commented May 31, 2019 at 9:19
  • Something like the posted answer. Commented May 31, 2019 at 9:20

1 Answer 1

1

Here's a vectorized way leveraging broadcasting, meant for performance efficiency -

bs = b*np.std(b,axis=0,keepdims=True)
c_out = (bs[:,None,:]+a).reshape(len(b),-1)

Sample run -

In [43]: N,M,D = 2,4,3
    ...: np.random.seed(0)
    ...: a = np.random.rand(N,D)
    ...: b = np.random.rand(M,D)
    ...: c = np.zeros((M,D*N))
    ...: 
    ...: c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
    ...: c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]    
    ...: c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2] 
    ...: 
    ...: c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
    ...: c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1] 
    ...: c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2]

In [44]: c
Out[44]: 
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])

In [45]: bs = b*np.std(b,axis=0,keepdims=True)
    ...: c_out = (bs[:,None,:]+a).reshape(len(b),-1)

In [46]: c_out
Out[46]: 
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])
Sign up to request clarification or add additional context in comments.

2 Comments

Okay thank you, will this take more memory? because I want to use large dimensions later
@ElenaPopa This will take as much memory as needed to get the final output.

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.