2

I am trying to cummatively add a value to the previous value and each time, store the value in an array.

This code is just part of a larger project. For simplicity i am going to define my variables as follows:

ele_ini = [12]
smb = [2, 5, 7, 8, 9, 10]

val = ele_ini
for i in range(len(smb)):
     val += smb[i]
     print(val)
     elevation_smb.append(val)

Problem

Each time, the previous value stored in elevation_smb is replaced by the current value such that the result i obtain is:

elevation_smb = [22, 22, 22, 22, 22, 22]

The result i am expecting however is

elevation_smb = [14, 19, 26, 34, 43, 53]

NOTE: ele_ini is a vector with n elements. I am only using 1 element just for simplicity.

user2554925
  • 487
  • 2
  • 8

3 Answers3

4

Don use loops, because slow. Better is fast vectorized solution below.

I think need numpy.cumsum and add vector ele_ini for 2d numpy array:

ele_ini = [12, 10, 1, 0]
smb = [2, 5, 7, 8, 9, 10]

elevation_smb  = np.cumsum(np.array(smb)) + np.array(ele_ini)[:, None]
print (elevation_smb)
[[14 19 26 34 43 53]
 [12 17 24 32 41 51]
 [ 3  8 15 23 32 42]
 [ 2  7 14 22 31 41]]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

Do with reduce,

In [6]: reduce(lambda c, x: c + [c[-1] + x], smb, ele_ini)
Out[6]: [12, 14, 19, 26, 34, 43, 53]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
2

It seems vector in your case is using pointers. That's why it is not creating new values. Try adding copy() which copies the value.

elevation_smb.append(val.copy())
Melug
  • 1,023
  • 9
  • 14