简体   繁体   中英

Apply transformation to a Numpy vector using values in other vectors

Suppose I have a 1D Numpy array t (say of length len_t ) containing values I want to apply a certain mathematical transformation. Along this, suppose I have 4 1D Numpy arrays a1 , k1 , k2 and d , all of same length (say len_p ).
The mathematical transformation I want to apply to t involves all these parameters. Therefore, I want to end up with a Numpy array of shape (len_p, len_t) containing transformed values of t transformed using each values of a1 , k1 , k2 and d one by one. For more precision, the transformation I want to apply is
y = (a1*(t - d)*k1)/(k2+l1)*np.exp(l1*(t - d))
where l1 is a simple float. I did not precise indices not to overweight notation. If my explanation is unclear, please tell me.
Does anybody have an idea on how I should proceed? I do not show more code as I will proceed to other similar transformations in the future and therefore need a general method.

EDIT

As an example, let us say

t = [0 1 2]

and

a1 = [.5 .1]
k1 = [.01 .3]
k2 = [.7 .03]
d = [.2 .41]
l1 = 2

What I want to get is a 2D array such that each row contains t values transformed by a set of parameters having the same indices in a1 , k1 , k2 and d . Therefore, the output would be

y = [[(a1[0]*(t[0] - d[0])*k1[0])/(k2[0]+l1)*np.exp(l1*(t[0] - d[0])) (a1[0]*(t[1] - d[0])*k1[0])/(k2[0]+l1)*np.exp(l1*(t[1] - d[0])) (a1[0]*(t[2] - d[0])*k1[0])/(k2[0]+l1)*np.exp(l1*(t[2] - d[0]))]
[(a1[1]*(t[0] - d[1])*k1[1])/(k2[1]+l1)*np.exp(l1*(t[0] - d[1])) (a1[1]*(t[1] - d[1])*k1[1])/(k2[1]+l1)*np.exp(l1*(t[1] - d[1])) (a1[1]*(t[2] - d[1])*k1[1])/(k2[1]+l1)*np.exp(l1*(t[2] - d[1]))]]

So, with numerical values, it goes

y = [[(.5*(0 - .2)*0.01)/(.7+2)*np.exp(2*(0 - .2)) (.5*(1 - .2)*0.01)/(.7+2)*np.exp(2*(1 - .2)) (.5*(2 - .2)*0.01)/(.7+2)*np.exp(2*(2 - .2))]
    [(.1*(0 - .41)*.3)/(.03+2)*np.exp(2*(0 - .41)) ((.1*(1 - .41)*.3)/(.03+2)*np.exp(2*(1 - .41)) (.1*(2 - .41)*.3)/(.03+2)*np.exp(2*(2 - .41))]]

First convert your variables to Numpy arrays:

  • t - to "ordinary" (row) array,
  • all other - to columnar arrays (something like you used np.newaxis in the simplified expression):

The code to do it is:

t  = np.array(t)
a1 = np.c_[np.array(a1)]
k1 = np.c_[np.array(k1)]
k2 = np.c_[np.array(k2)]
d  = np.c_[np.array(d)]

Then run your simplified expression:

y = (a1 * (t - d) * k1)/(k2 + l1) * np.exp(l1 * (t - d))

To compare both results (yours and mine) run np.set_printoptions(suppress=True) before. Otherwise the results would be printed in "exp" notation, what impedes comparison. You may also adjust precision option.

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