Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top n rows in a matrix?

I'm trying to figure out the best way of doing this, ideally in Octave, but I'll take NumPy at a pinch.

Let's say I have an axb matrix M. If I want the row indices of the maximum value in any given column, [x, xi] = max(M) will return these indices for me as a row vector.

For example, if M is:

1  3  5 
2  9  1
7  2  4

The above will return row vector [3 2 1] as xi; A vector of the indices of each row which contains the maximum value for that column. This is good. I want this row vector.

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

[edited to explain this better]

For the above example, the first such vector would be the above [3, 2, 1], (the indices of the rows with the highest values for each given column). The second such vector would be [2 1 3], (the indices of the rows with the second-highest values for each column).

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

like image 941
R Hill Avatar asked Jan 13 '23 03:01

R Hill


1 Answers

I assume that you mean you want the n biggest values from the matrix. In which case, Get the indices of the n largest elements in a matrix is almost the same question as this, except there the OP wanted the largest values of the whole matrix, not individual maximums. This should get you 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
like image 155
slbass Avatar answered Jan 16 '23 18:01

slbass