find the largest value and its index using for loop and if statements

I am new to matlab and don't know how to solve this: I need to write a script using combination of a 'for' loop and 'if' statements to find the largest value of a vector and its index. myvar=[10 1 3 6 8 3 6 9 3 1 6 9 12 7 5 3 6 8 2 1] Thanks for help! Marta

2 Comments

What have you got so far?
HW help in Answers/newsgroup is generally directed to specific questions of syntax or the like after the poster shows good-faith effort in solving the problem first. We do NOT solve HW problems first go...

Sign in to comment.

Answers (2)

This oughtta do it:
myvar=[10 1 3 6 8 3 6 9 3 1 6 9 12 7 5 3 6 8 2 1];
for ii = 1
if ii
[max_val,idx] = max(myvar);
end
end
so far I got this
for i=1:20
if myvar(i)>max
save = myvar(i)
max = myvar(i)
end
end
the code doesn't work, and am not sure how to get the index part also. I read help on 'for' loop and 'if' however i am still confused:(

2 Comments

save should just be i since this is the index. Also, you should set max to -inf first so that it's guaranteed to pass on the first iteration.
Sean, come on! You forgot to mention that it's bad practice to name your variables after built-in functions such as save() and max(). The reason why is probably doesn't work is this: if myvar(i)>max. The first time through, max is the built-in max function and it probably barfs at that point because no arguments have been supplied. Secondly, to be a little more robust and flexible, 20 should be replaced by length(myvar). Third, don't use i and j as indexes - they can but they are also the complex number so people usually avoid them, and use something like k instead. Lastly, you need to save the index k. Just two lines of code inside the "if" should suffice
if myvar(k) > theMaxValue
theMaxValue = myvar(k);
theIndexAtMax = k;
end

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 13 Sep 2013

Community Treasure Hunt

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

Start Hunting!