find max of vector

조회 수: 24 (최근 30일)
diadalina
diadalina 2019년 12월 2일
댓글: James Tursa 2019년 12월 5일
i want to find the maximum of a vector and its position, if i have for example v=[-1,3,4,5,-2,5] , the max is 5 but i have two positions , how can i find these two positions using for loops , here is my program but it doesn't work :
v=[-1,3,4,5,-2,5]
maxi=v(1);
j=1;
for i=2:length(v)
if v(i)>maxi
maxi=v(i);
pos(j)=i;
j=j+1;
end
end

답변 (2개)

the cyclist
the cyclist 2019년 12월 2일
m = max(v);
idx = find(v==m);
  댓글 수: 1
diadalina
diadalina 2019년 12월 2일
thank you mr cyclist for your answer, but i want the loops for way

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


James Tursa
James Tursa 2019년 12월 2일
편집: James Tursa 2019년 12월 2일
Two things. FIrst, you need to initialize pos = 1 before the loop starts. And second, you need to modify your if-test to do two things: If v(i) == maxi, then add another pos(j) similar to what you are currently doing, but if v(i) > maxi then you need to start over and save a new max. Currently you keep adding in new pos(j) values when a new max is found but not getting rid of the old ones. E.g.,
if v(i) == maxi
j=j+1;
pos(j)=i;
elseif v(i) > maxi
% code to save new max value in maxi, and start over with pos = i etc.
end
I will leave it to you to fill in the missing code.
  댓글 수: 4
diadalina
diadalina 2019년 12월 3일
v=[-1,3,4,5,-2,5]
maxi=v(1);
j=1;;
pos=1;
for i=2:length(v)
for j= 1:length(v)
if v(i) == maxi
maxi=v(i);
pos(j)=i;
else if v(i)>maxi
pos = i;
maxi=v(i);
j=1;
end
end
end
end
it doesn't work alsopos =
6 6 6 6 6 6
maxi =
5
James Tursa
James Tursa 2019년 12월 5일
We seem to be diverging here, and you are not implementing my advice. For example, now you have two for-loops:
for i=2:length(v)
for j= 1:length(v)
Why are you suddenly introducing an additional for-loop?
And you still haven't implemented the code I gave you for the v(i) == maxi case.

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

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by