Top n rows in a matrix?

I'm trying to find a better way to do this, ideally in Octave, but I'll take NumPy as a last resort.

Say I have an axb matrix M. If I need row indexes of the maximum value in any column, [x, xi] = max(M) will return these indexes for me as a row vector.

For example, if M:

 1 3 5 2 9 1 7 2 4 

The above will return the row vector [3 2 1] as xi ; The index vector of each row that contains the maximum value for this column. It's good. I want this row vector.

But what if I want the top n such row vectors?

[edited to explain it better]

In the above example, the first such vector will be the above [3, 2, 1] (row indices with the highest values ​​for each given column). The second such vector will be [2 1 3] (row indices with second highest values ​​for each column).

I could do it iteratively, but my actual matrices have many thousands of rows, so that would be quite expensive. I cannot find any obvious matrix utility function to help me with this. Any suggestions?

+4
source share
3 answers

I assume that you mean that you want to get the largest values ​​from the matrix. In this case, Obtaining indices from the n largest elements in the matrix is almost the same question as this one, except that the OP wanted to get the largest values ​​of the entire matrix, rather than individual maxima. This should provide you with what you need.

 n = 2; % The depth to get M = [ 1, 3, 5; ... 2, 9, 1; ... 7, 2, 4 ]; % The matrix to look at [m, mi] = sort(M, 'descend'); % Sort the to access them x = m(1:n, :) % Get the values xi = mi(1:n, :) % and the indices 
+5
source

Like this?

 % N is the number of rows you want to include. [x, xi] = max(a(1:N,:)) 

This gives you:

 a = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1 N = 3; [x, xi] = max(a(1:N,:)) x = 16 11 10 13 xi = 1 2 2 1 
+2
source

Here's how to do it in numpy. Please see numpy.argmax , which returns the maximum value indices along the axis. Note that these indexes are based on 0, so you might want to add / subtract 1 on it to make it 1 based on like in matlab.

Taking the same example @Stewie Griffin :-)

 In [3]: a = np.array([[16,2,3,13], [5,11,10,8], [9,7,6,12], [4,14,15,1]]) In [4]: N = 2 # A 0-based index In [5]: np.argmax(a[N], axis=0) Out[5]: array([0, 1, 1, 0]) 

Here the axis is 0 because you want the maximum indices in each column. Change it to 1 if you want maximum indices in each raw. Also numpy.argmin if you want min.


Based on your explanation, you want the nth largest indices in each column, which is very easy with numpy.argsort .

 In [11]: A = np.argsort(a, axis=0) # returns indices of smallest to largest values in each column In [12]: A Out[12]: array([[3, 0, 0, 3], [1, 2, 2, 1], [2, 1, 1, 2], [0, 3, 3, 0]]) In [13]: N = 1 # 0-based index In [14]: A[N] # 2nd smallest indices Out[14]: array([1, 2, 2, 1]) In [14]: A[-N-1] # 2nd largest indices Out[14]: array([2, 1, 1, 2]) 
+2
source

Source: https://habr.com/ru/post/1486831/


All Articles