becs
becs

Reputation: 83

Is there a faster way to implement this looping function?

Is there any way I can make this function faster?? I am trying to create the 3 x 3 alpha_j matrix defined by:

enter image description here

I have,

def a_j(r, a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    for i in range(3):
        for j in range(3):
            alph[i,j] = (r * a * A[i,j])
    return alph

Upvotes: 1

Views: 62

Answers (2)

Sheri
Sheri

Reputation: 1413

You can do it without any loop:

def a_j(r, a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    alph= (r * a * A)
    return alph
r = 5
a = 10
A = np.array([[2,6,1],[0,4,9],[1,8,3]],complex)
ans  = a_j(r,a,A)
print(ans)

Output of this code:

[[ 100.+0.j  300.+0.j   50.+0.j]                                                                                    
 [   0.+0.j  200.+0.j  450.+0.j]                                                                                    
 [  50.+0.j  400.+0.j  150.+0.j]] 

Output of your code:

[[ 100.+0.j  300.+0.j   50.+0.j]                                                                                    
 [   0.+0.j  200.+0.j  450.+0.j]                                                                                    
 [  50.+0.j  400.+0.j  150.+0.j]] 

Notice outputs are same means you can do it without any for loop

Upvotes: 2

Julien Roullé
Julien Roullé

Reputation: 662

You could use list of comprehension, like this:

def a_j(r, a, A):
    return np.array([[np.complex(r * a * A[i,j]) for j in range(3)] for i in range(3)])

Upvotes: 0

Related Questions