I have a numpy array of 5 numpy arrays, each with 5 observations. I need to use the trapezoid rule of integration to get 5 results of integrating. I'm trying to use for loop for apply a function to each numpy array and looking for something that has faster implementation.
def trapezoid_rule(a,b,n,f_nparray):
h = (b-a) / (n-1)
return (h/2) * (f_nparray[0] + 2 * sum(f_nparray[1:n-1]) + f_nparray[n-1])
simulation_res = np.array([[1,2,3,4,5], [1,3,5,7,9], [1,4,2,5,7], [1,5,2,6,4], [6,2,5,3,4]])
# List of integration results
I = []
for i in simulation_res:
I.append(trapezoid_rule(0,1,10,i))
Expected output format = [a,b,c,d,e]
(f_nparray[:, [0]] + 2 * sum(f_nparray[:, 1:n-1]) + f_nparray[:, [n-1]])- applying thetrapezoid_rulefunction to all rows at once. The trickiest part is getting the 3 terms to work together, with therules of broadcasting. shapes: (n,1), (n,m), (n,1)