Home > Net >  sum over inputs of three arrays in python
sum over inputs of three arrays in python

Time:10-09

I have 3 arrays named R, p and k and i also have an expression. I want to compute this expression for the first value of R and the whole values of p and k. then sum all the result obtained from this step and put them into a new array as the first element. Then compute the mentioned expression for the second value of R and every values of p and k. Then, again sum all the results of the second step and put them into a new array as the second element and so on ... I do some coding but I don't know how to continue it. I would appreciate it if you help me.

import numpy as np
R = [1,4,6]
p = [6,4,1]
k = [8,5,2]
sigma = np.zeros(len(R))
for i in range(len(R)):
    for j in range(len(k)):
        sigma = (p[j] k[j]*R[i])
        print(sigma)

How can I sum the values resulted from first (second etc,) R and append them into a new array?

CodePudding user response:

You could try using list comprehensions.

It's basically translated as, for each i in R, calculate sigma for each pair in p,k

R = [1,4,6]
p = [6,4,1]
k = [8,5,2]

[[a b*i for a,b in zip(p,k)] for i in R]

Output

[[14, 9, 3], [38, 24, 9], [54, 34, 13]]

CodePudding user response:

import numpy as np
R = [1,4,6]
p = [6,4,1]
k = [8,5,2]
ans = np.zeros(len(R))
for i in range(len(R)):
    sigma = 0 #for each value in R  calculated value initialized to 0
    for j in range(len(k)):
        #loop through second array and compute the expression
        sigma  = p[j] k[j]*R[i]
    ans[i]=sigma #add value to answers list after second loop
print(ans)
  • Related