second maximum- not returning index

조회 수: 2 (최근 30일)
Sara Ismail-Sutton
Sara Ismail-Sutton 2020년 11월 21일
댓글: Sara Ismail-Sutton 2020년 11월 22일
Used the following code:
function [i,y] = second_max( x )
[a,b]=max(x)
[i,y] = max(x(x==a))
end
e.g I test this with vector [ 1 2 3 4 4 3 2 1], expecting i to give 5 - the value of the second maximum, but instead it is returning y and I am not sure why??
Many thanks !

답변 (1개)

Image Analyst
Image Analyst 2020년 11월 21일
True. That's just the way max() works. It only returns the first index if the max exists at multiple indexes. To find all the indexes where the max occurs you need to use find():
maxValue = max(x)
indexes = find(x == maxValue)
  댓글 수: 1
Sara Ismail-Sutton
Sara Ismail-Sutton 2020년 11월 22일
okay many thanks for your reply, I don't suppose you could help with my next issue.
The issue is with line 18 of the code below. I tested it with the vector C =[1 2 3 4 4 3 2 1], and used the de-bugging step, to view it step by step, and it skips past the if statement on line 18 " if ((find(M(i,:)==val(i)))==1) " whereas this should return a match with the value of 4 at index 4 to the value of 4 at indedx 5. I can not work out why it is skipping back this - i.e. returning a negative for the find value. Many thanks in advance :) (for more background the function is trying to find a saddle point, I'm aware it's probbaly not optimal etc but I think it's best if I learn that myself, and for now if someone could just address my question above. Many thanks ! )
function[indices]=checkingrow(M)
[ b1 b2] = size (M);
%for each row get vector of values
%and vector of indexes seperately
indices=[0,0];
for i=1:b1;
[val(i)]=max(M(i,:));
[~, c]=max(M(i,:));
[k,l]=min(M(:,c));
if l==i
indices=[i,c]
if ((find(M(i,:)==val(i)))==1)
[ind(i)] = find(M(i,:) == val(i))
[z,w]=min(M(:,ind(i)));
if ind(i)==w
indices2=[i,w]
end
end
else indices=indices;
end
end
if indices==[0,0]
indices=zeros(b1,b2)
end
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by