find max of vector
30 views (last 30 days)
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 :
James Tursa on 2 Dec 2019
Edited: James Tursa on 2 Dec 2019
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
elseif v(i) > maxi
% code to save new max value in maxi, and start over with pos = i etc.
I will leave it to you to fill in the missing code.