Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max value per diagonal in 2d array

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?

like image 507
jezrael Avatar asked Dec 04 '19 09:12

jezrael


People also ask

How do you find the maximum sum of a 1D array?

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.

How to calculate the sum of diagonal elements in a matrix?

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.

How do you find the row number of a diagonal array?

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.

How to store diagonal elements in an array of vectors?

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.


1 Answers

Use ndarray.diagonal

v = [max(c.diagonal(-i)) for i in range(b.shape[0])]
print(v) # [0, 13, 3, 6, -4]
like image 95
Guy Avatar answered Sep 21 '22 06:09

Guy