Jurgen Cuschieri
Jurgen Cuschieri

Reputation: 736

Get row value of 3 largest elements in column

I am a beginner at Matlab with no previous experience. Just started using it now as I had no other choice.

So let's say I have a 12 row 155 column matrix. I want to traverse the columns, sorting each one on the way. I found various methods getting N largest elements out of a matrix, but what is important to me is not the value of the element but the row index in which it appeared originally.

For example:

column: 5, 4, 3, 2, 6, 8, 9, 10, 1, 12, 7, 11

The 3 largest elements are 10, 11 and 12. And they are in 8th, 10th and 12th row. The index of the row has meaning to me so that's what matters.

For now I have this piece of code which supposedly sets a for loop to traverse the whole matrix, C.

[rows,cols] = size(C);
for col = 1:cols
    for row = 1:rows
        %Sort the column in ascending order. Return 3 largest rows

    end
end 

Any suggestions to how I can achieve this? Thanks in advance for your time.

Upvotes: 0

Views: 102

Answers (2)

beaker
beaker

Reputation: 16810

You can sort the entire array, or you can find the maximum of each column 3 times:

Original=randi(1000,20,5);
C=Original;   %// Make a copy because we're going to modify it
sizeC=size(C);
k=3;
maxIndices=[];
for n=1:k
   [~,Idx]=max(C);
   maxIndices(end+1,:)=Idx;
   C(sub2ind(sizeC,Idx,[1:numel(Idx)]))=-inf;
end

With an input matrix C of:

C =

   782   667   458   235   153
   220   170   902   475   968
   829   554   291   245   834
    60   355   120   670   165
   194   981   805   348    27
   632   939   215   198   405
   296   270    61   745   601
   695   956   190   564   593
    44   681   832   526   856
   420   560   891   955   126
   294   682   878   129   699
   184   470   332   915   883
   303   888   919   996    43
   392   572   284   836   839
   245   640   127   575    63
   996   156   296   558   746
   248   770    73   697   678
   675   522   541   255   891
   691   527   643    75   821
    92   111   426   887   327

the output is:

maxIndices =

   16    5   13   13    2
    3    8    2   10   18
    1    6   10   12   12

Largest value for each column is in the first row, second largest in the second row.

Upvotes: 2

TyanTowers
TyanTowers

Reputation: 160

>> A = [2 4 5 12 3;7 2 7 4 8;2 7 4 8 2;3 7 2 9 5]

A =

 2     4     5    12     3
 7     2     7     4     8
 2     7     4     8     2
 3     7     2     9     5

>> [a,I] = sort(A);
>> I(1:3,:)

ans =

 1     2     4     2     3
 3     1     3     3     1
 4     3     1     4     4

Upvotes: 2

Related Questions