How do you rewrite the nested if statement as a loop?

조회 수: 2 (최근 30일)
Jillian Sweatt
Jillian Sweatt 2017년 2월 2일
편집: Adam 2017년 2월 2일
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

채택된 답변

Adam
Adam 2017년 2월 2일
편집: Adam 2017년 2월 2일
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개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by