I am comparing the values of the elements 1 to n-1 of an array with their two direct neigbours (left and right). In order to find out, how many elements are smaller or bigger than both of their neigbours I implemented a counter starting at the value 0.
The comparision is done by a simple iteration in a "for"-loop. For each iteration i, the assigned counter value val[i] should be computed in dependency of the previous counter value val[i-1]. In theory, the value can only remain constand or incease by 1. However, in my loop the counter sometime resets to 0 or substacts 1.
Even after trying a lot of things, like changing the number of indexing brackets, I was not able to fix this substraction problem. Can anyone see whats the problem with my code and tell me how to resolve this issue?
The correct output, would expect the array val = [ 0, 0, 1, 2, 2, 2, 2, 3, 4]
duv = np.array([24, 12, 0, 6, 3, 0, -3, -6, -3, -6])
val = []
val = np.append(val, 0)
print('start_val = ', val[0])
for i in range (1, 9):
if duv[[i-1]] > duv[[i]] and duv[[i 1]] > duv[[i]]:
new_val = val[[i-1]] 1
val = np.append(val, new_val)
if duv[[i-1]] < duv[[i]] and duv[[i 1]] > duv[[i]]:
new_val = val[[i-1]] 1
val = np.append(val, new_val)
else:
new_val = val[[i-1]]
val = np.append(val, new_val)
print(val)
CodePudding user response:
Use vectorial code.
Here using the sign of the shifted difference and a cumsum
:
duv = np.array([24, 12, 0, 6, 3, 0, -3, -6, -3, -6])
diff = np.sign(np.diff(duv))
diff1 = np.r_[0, diff]
diff2 = np.r_[-diff, 0]
out = np.cumsum(diff1 == diff2) #[:-1] # if the last element is unwanted
output: array([0, 0, 1, 2, 2, 2, 2, 3, 4, 4])