0

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.

3 Answers 3

1

Make a 51 X 4 array with your Ks 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
Sign up to request clarification or add additional context in comments.

Comments

1
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() 




Comments

1
  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)

2 Comments

Paul, thanks for answering. I'm trying to code this at the moment, but frankly, to me that looks like a terribly overcomplex way of calculating this thing. Setting constants as arrays, setting arrays as arrays-of-arrays, ... Is there a more intuitive way of doing this thing (something, that will enable someone not familiar with what I'm trying to do, to figure out what way being done, by reading the code afterwards?)
it's the most numpy-kind approach. with most internal optimisations. it's not very complex in the code, tho. I'll update an answer with a draft

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.