For loop to count matrix elements

5 views (last 30 days)
Kyle
Kyle on 14 Mar 2014
Answered: Jos (10584) on 14 Mar 2014
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 Comment
per isakson
per isakson on 14 Mar 2014
Edited: per isakson on 14 Mar 2014
  • The exact value 200 fits in two cases, amount5 and amount6
  • add else to pick up mistakes

Sign in to comment.

Answers (1)

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

Categories

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

Tags

Community Treasure Hunt

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

Start Hunting!