I have array and need max of rolling difference with dynamic window.
a = np.array([8, 18, 5,15,12])
print (a)
[ 8 18 5 15 12]
So first I create difference by itself:
b = a - a[:, None]
print (b)
[[ 0 10 -3 7 4]
[-10 0 -13 -3 -6]
[ 3 13 0 10 7]
[ -7 3 -10 0 -3]
[ -4 6 -7 3 0]]
Then replace upper triangle matrix to 0:
c = np.tril(b)
print (c)
[[ 0 0 0 0 0]
[-10 0 0 0 0]
[ 3 13 0 0 0]
[ -7 3 -10 0 0]
[ -4 6 -7 3 0]]
Last need max values per diagonal, so it means:
max([0,0,0,0,0]) = 0
max([-10,13,-10,3]) = 13
max([3,3,-7]) = 3
max([-7,6]) = 6
max([-4]) = -4
So expected output is:
[0, 13, 3, 6, -4]
What is some nice vectorized solution? Or is possible some another way for expected output?
If we apply Kadane’s 1D algorithm on temp [], and get the maximum sum subarray of temp, this maximum sum would be the maximum possible sum with left and right as boundary columns. To get the overall maximum sum, we compare this sum with the maximum sum so far. // 1D array. The function returns the maximum // respectively.
create a double dimension array of size 4 x 4 and calculate the sum of the diagonal elements. In a square matrix diagonal elements are two type. In case of left diagonal the row number and column number are same. that is row no = col no.
In case of left diagonal the row number and column number are same. that is row no = col no. And in case of right diagonal row number + column number = (Total row number - 1). Therefore, we just travel the array once and add all the elements which meet the above conditions.
The cells having the same difference from top-left to bottom-down cell forms a diagonal. Store the diagonal element with a positive difference in one Array of Vectors (say Pos []) such that elements at the cell having difference (say a) is stored at index an of Pos [] array.
Use ndarray.diagonal
v = [max(c.diagonal(-i)) for i in range(b.shape[0])]
print(v) # [0, 13, 3, 6, -4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With