简体   繁体   English

如何在Python或NumPy循环中计算此方程式?

[英]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)? 在Python(或NumPy,如果您认为这种操作更可取)中循环计算此值的最佳方法是什么?

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). 其中K0是一个数组,包含51个系数(浮点数)。 The same for K1, K2 and K3. K1,K2和K3相同。
Var0, Var1, Var2 and Var3 are constants. Var0,Var1,Var2和Var3是常数。

KT is the result, depending on Var0, ... Var3. KT是结果,取决于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. 我来自Fortran,目前正在使用Python学习/实验,因此请原谅新手问题。 Python loops sometimes behave un-intuitively to me. Python循环有时对我而言是不直观的。

Make a 51 X 4 array with your K s and a 4 X 1 array with you X and multiply. 做一个51 X 4阵列的K S和4 X 1阵列与你X和繁殖。 Numpy has something called broadcasting that will expand X to be multiplied with every row of K. Numpy有一种叫做广播的东西,它将扩展X使其与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] 将Vars修复为一个numpy数组[Var0,Var1,..,VarN]
  2. Fix K is a numpy array of arrays [[K11, K12,..,K1N][K21, K22,..,K2N],...] Fix K是数组[[K11,K12,..,K1N] [K21,K22,..,K2N],...]的一个小数数组
  3. Write a lambda function for multiplying Var_row * K_row 编写一个lambda函数以乘以Var_row * K_row
  4. Vectorize this function using numpy (np.vectorize) 使用numpy向量化此函数(np.vectorize)
  5. Apply vectorized function over data massive (2) 将矢量化功能应用于海量数据(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() 




声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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