For loop to count matrix elements

2 visualizaciones (últimos 30 días)
Kyle
Kyle el 14 de Mzo. de 2014
Respondida: Jos (10584) el 14 de Mzo. de 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 comentario
per isakson
per isakson el 14 de Mzo. de 2014
Editada: per isakson el 14 de Mzo. de 2014
  • The exact value 200 fits in two cases, amount5 and amount6
  • add else to pick up mistakes

Iniciar sesión para comentar.

Respuestas (1)

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

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by