How do you rewrite the nested if statement as a loop?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
for i=1:length(x)
if x(i) >= -1 && x(i) <= -0.9
count(1) = count(1)+1;
elseif x(i) >-0.9 && x(i)<-0.8
count(2) = count(2)+1;
elseif x(i)>-0.8 && x(i)<-0.7
count(3) = count(3)+1;
elseif x(i)>-0.7 && x(i)<-0.6
count(4) = count(4)+1;
elseif x(i)>-0.6 && x(i)<-0.5
count(5) = count(5)+1;
elseif x(i)>-0.5 && x(i)<-0.4
count(6) = count(6)+1;
elseif x(i)>-0.4 && x(i)<-0.3
count(7) = count(7)+1;
elseif x(i)>-0.3 && x(i)<-0.2
count(8) = count(8)+1;
elseif x(i)>-0.2 && x(i)<-0.1
count(9) = count(9)+1;
elseif x(i)>-0.1 && x(i)<0
count(10) = count(10)+1;
elseif x(i)>0 && x(i)<0.1
count(11) = count(11)+1;
elseif x(i)>0.1 && x(i)<0.2
count(12) = count(12)+1;
elseif x(i)>0.2 && x(i)<0.3
count(13) = count(13)+1;
elseif x(i)>0.3 && x(i)<0.4
count(14) = count(14)+1;
elseif x(i)>0.4 && x(i)<0.5
count(15) = count(15)+1;
elseif x(i)>0.5 && x(i)<0.6
count(16) = count(16)+1;
elseif x(i)>0.6 && x(i)<0.7
count(17) = count(17)+1;
elseif x(i)>0.7 && x(i)<0.8
count(18) = count(18)+1;
elseif x(i)>0.8 && x(i)<0.9
count(19) = count(19)+1;
elseif x(i)>0.9 && x(i)<=1
count(20) = count(20)+1;
end
end
0 Kommentare
Akzeptierte Antwort
Adam
am 2 Feb. 2017
Bearbeitet: Adam
am 2 Feb. 2017
lowLims = -1:0.1:0.9;
highLims = -0.9:0.1:1;
count = sum( x > lowLims & x <= highLims );
should work though I replaced the < with a <= because e.g. 0.1 will not fall into any case. Maybe this is your intention, in which case just put the < back and it should still work.
Use vectorisation instead of a loop when you can, though it is fine to go via a loop first if it is easiest. Certainly you don't ever want a massive structure of it-else statements like yours though that is hard to maintain and liable to bugs as well as being unreadable.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!