フィルターのクリア

second maximum- not returning index

3 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by