For loop to count matrix elements

조회 수: 2 (최근 30일)
Kyle
Kyle 2014년 3월 14일
답변: Jos (10584) 2014년 3월 14일
Hi all i'm trying to use a for loop ( for an assingmnet) to run through a 5000 element matrix ( which I've downloaded manually) and determine which variables fall under certain conditions ( hopefully they're apparent in the code). i think i've set everything up right but I'm getting output for only about 3700 numbers. also, i noticed i'm not getting any output for "f"... if x(n) > 200... even though i have several values that fall under this category in my matrix. any idea why this isn't working? i feel like it should be.
amount=0;
amount1=0;
amount2=0;
amount3=0;
amount4=0;
amount5=0;
amount6=0;
for n=1:length(x)
if x(n)>=0 && x(n)<= 30
amount=amount+1 ;
elseif x(n) >=30 && x(n)<=80
amount1=amount1+1 ;
elseif x(n) >= 80 && x(n)<=130
amount2=amount2+1 ;
elseif x(n) >= 130 && x(n) <= 150
amount3=amount3+1;
elseif x(n) >=150 && x(n)<=180
amount4=amount4+1 ;
elseif x(n) >= 180 && x(n) x<=200
amount5=amount5+1 ;
elseif x(n) >= 200
amount6=amount6+1 ;
end
end
% a,b,c,d,e,f are used to display final count values
a=amount
b=amount2
c=amount3
d=amount4
e=amount5
f=amount6
  댓글 수: 1
per isakson
per isakson 2014년 3월 14일
편집: per isakson 2014년 3월 14일
  • The exact value 200 fits in two cases, amount5 and amount6
  • add else to pick up mistakes

댓글을 달려면 로그인하십시오.

답변 (1개)

Jos (10584)
Jos (10584) 2014년 3월 14일
Why not use HISTC to count elements falling in a specific range?
amount = histc(x,[0 30 80 130 150 200 Inf])

카테고리

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