find the largest value and its index using for loop and if statements
Ältere Kommentare anzeigen
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 Kommentare
Azzi Abdelmalek
am 13 Sep. 2013
Is it a homework ?
dpb
am 13 Sep. 2013
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...
Antworten (2)
Sean de Wolski
am 13 Sep. 2013
Bearbeitet: Sean de Wolski
am 13 Sep. 2013
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
marta
am 13 Sep. 2013
Bearbeitet: Sean de Wolski
am 13 Sep. 2013
2 Kommentare
Sean de Wolski
am 13 Sep. 2013
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.
Image Analyst
am 13 Sep. 2013
Bearbeitet: Image Analyst
am 13 Sep. 2013
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
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!