简体   繁体   中英

How to calculate this equation in Python or NumPy loop?

What is the best way to calculate this in a loop in Python (or NumPy, if you think it is preferred for this kind of operation)?

KT = K0[1]*Var0 + K1[1]*Var1 + K2[1]*Var2 + K3[1]*Var3 +
     K0[2]*Var0 + K1[2]*Var1 + K2[2]*Var2 + K3[2]*Var3 +
     ...
     K0[51]*Var0 + K1[51]*Var1 + K2[51]*Var2 + K3[51]*Var3

where K0 is an array, containing 51 coefficients (floats). The same for K1, K2 and K3.
Var0, Var1, Var2 and Var3 are constants.

KT is the result, depending on Var0, ... Var3. The coefficient arrays are always the same. They do not change.

I'm coming from Fortran, and am currently learning/experimenting with Python, so forgive maybe the novice question. Python loops sometimes behave un-intuitively to me.

Make a 51 X 4 array with your K s and a 4 X 1 array with you X and multiply. Numpy has something called broadcasting that will expand X to be multiplied with every row of K.

import numpy as np
K = np.column_stack([k0, k1, k2, k3])
X = np.array([x0, x1, x2, x3])
result = K * X
  1. Fix Vars as a numpy array[Var0, Var1,..,VarN]
  2. Fix K is a numpy array of arrays [[K11, K12,..,K1N][K21, K22,..,K2N],...]
  3. Write a lambda function for multiplying Var_row * K_row
  4. Vectorize this function using numpy (np.vectorize)
  5. Apply vectorized function over data massive (2)
  6. Be happy =)

a draft:

V_arr = np.array([2, 2, 2, 2])
K_arr = np.array([[1, 2, 3, 4],[4, 3, 2, 1],[5, 4, 4, 4]])

def mult_arr(a, b):
   return a * b

mult_vector = np.vectorize(mult_arr)

res = mult_vector(K_arr, V_arr)
num1 = np.multiply(K0, var0) # type: numpy array
num2 = np.multiply(K1, var1)
num3 = np.multiply(K2, var2)
num4 = np.multiply(K3, var3)
# (num1 + num2 + num3 + num4) will give a single numpy array and then sum() operation will give you summation of all elemnts
KT = (num1 + num2 + num3 + num4).sum() 




The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM