# findout the second largest element in each row and its location in a matrix

조회 수: 197(최근 30일)
navan 20 May 2015
답변: Steven Lord 28 Oct 2018
I have a (3*5) matrix i.e A=[1 2 3 4 5, 6 7 9 8 10, 11 12 14 13 15], i would like to find out the second largest element in each row and its location in the matrix. i expect 2 outputs 1)second_maxvalue_A=[4,9,14] 2)location_of_second_maxval=[4,3,3]

로그인 to comment.

### 채택된 답변

Guillaume 20 May 2015
One possible way is to find the largest values, replace them with a very small value (-Inf) and search for the new largest values:
A=[1 2 3 4 5; 6 7 9 8 10; 11 12 14 13 15] %your example A was a single row
m = max(A, [], 2); %find the max in each row
A(bsxfun(@eq, A, m)) = -Inf; %replace the max(s) by -Inf
m = max(A, [], 2) %find the new max which is the second largest.

#### 댓글 수: 3

navan 20 May 2015
Thanks Guillaume,
That works.thanks alot
zahra najjar 28 Oct 2018
Bruno Luong 28 Oct 2018

로그인 to comment.

### 추가 답변(3개)

Steven Lord 28 Oct 2018
If you're using release R2017b or later, use maxk.

#### 댓글 수: 0

로그인 to comment.

Thomas Koelen 20 May 2015
편집: Thomas Koelen 20 May 2015
Edit: seems like I misread second largest...
, should be ;.
A=[1 2 3 4 5; 6 7 9 8 10; 11 12 14 13 15];
[m,i] = max(A,[],2)
gives you:
m =
5
10
15
i =
5
5
5
example:
A=rand(3,5);
[m,i] = max(A,[],2)
gives:
0.8147 0.9134 0.2785 0.9649 0.9572
0.9058 0.6324 0.5469 0.1576 0.4854
0.1270 0.0975 0.9575 0.9706 0.8003
m =
0.9649
0.9058
0.9706
i =
4
1
4

#### 댓글 수: 3

Thomas Koelen 20 May 2015
Finding second or third biggest can be done this way:
m=3;n=4;ggg = rand(m,n);
[svals,idx] = sort(ggg(:),'descend'); % sort to vector
svals(2) % second largest value
[II,JJ] = ind2sub([m,n],idx(2)) % position in the matrix
Guillaume 20 May 2015
Doesn't this find the second largest element in the matrix, rather than each row?
Secondly, if there are more than one element equal to the max, it still returns the max.
Guillaume 20 May 2015
A generic way of finding the nth largest value of each row, if it exists:
function nl = nthlargestrow(m, n)
%m: a 2d matrix to search
%n: an integer
%nl: cell array containing the nth largest value of each row. If a row does not have n different values, the cell is empty
nl = cell(size(m, 1), 1);
u = cellfun(@unique, num2cell(m, 2), 'UniformOutput', false);
hasnelements = cellfun(@numel, u) >= n;
nl(hasnelements) = cellfun(@(row) row(end-n+1), u(hasnelements), 'UniformOutput', false)
end

로그인 to comment.

Thorsten 20 May 2015
A=[1 2 3 4 5; 6 7 9 8 10; 11 12 14 13 15];
% remove highest value in each row
sz = size(A);
[~, ind] = max(A, [], 2);
ind = ind + [0; cumsum(repmat(sz(2), [sz(1)-1 1]))];
A = A';
A(ind) = [];
A = reshape(A, [sz(2)-1 sz(1)])';
% find highest value in each row (i.e., second largest of original matrix)
[max2, ind2] = max(A, [], 2);

#### 댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.