if statement problem

12 visualizaciones (últimos 30 días)
Hugo Policarpo
Hugo Policarpo el 26 de Ag. de 2011
Hello, I'm having some problems with an if statement. This is what I want to do: If x>1 A=B elseif x<1 and x>0.1 A=C elseif x<0.1 and x>0.01 A=D elseif x<0.001 A=F
I don,t seam to be able to get this working. Any help is welcome
Here is the code:
Y=random('unif',0.01,2,100,1);
for i=1:100
if Y(1:i,1)>=1
c(i,1)=1;
c(i,2)=0;
c(i,3)=0;
elseif (Y(1:i,1) < 1) && (Y(1:i,1) >= 0.1)
c(i,1)=1;
c(i,2)=0.5;
c(i,3)=0;
elseif (Y(1:i,1)<0.1) && (Y(1:i,1)>=0.01)
c(i,1)=1;
c(i,2)=1;
c(i,3)=0;
elseif Y(1:i,1)<0.01
c(i,1)=0;
c(i,2)=1;
c(i,3)=0;
end
end

Respuesta aceptada

Oleg Komarov
Oleg Komarov el 26 de Ag. de 2011
You should use:
Y(i,1)
instead of
Y(1:i,1)
Also preallocate c:
c = zeros(size(Y,1),3);
You can simply write:
if Y(i,1) < 0.01
...
elseif Y(i,1) < 0.1
...
elseif Y(i,1) < 1
...
else
...
end
  1 comentario
Hugo Policarpo
Hugo Policarpo el 26 de Ag. de 2011
Thanks,
the ":" where the problem.
solved

Iniciar sesión para comentar.

Más respuestas (2)

Sean de Wolski
Sean de Wolski el 26 de Ag. de 2011
if Y(1:i,1)>=1
let's say
Y = [0 1 2 3]' ;
for i = 1:4
if Y(1:i,1)>=1
disp('yup');
else
disp('nope');
end
end
What do you see?
All nopes, the way MATLAB is interpreting this is
if(all(Y(1:i,1))>1)
  • when i = 1,( Y(1:1,1) = 0 )> 1) nope
  • when i = 2, Y(1:2,1) = [0 1] > 1, are both of them? nope
  • when i = 3, Y(1:3,1) = [0 1 2] > 1, are all of them? nope
I think you probably want to change your if statement to Y(i,1) also look at
doc any
doc all
for more information

Jan
Jan el 26 de Ag. de 2011
Some of the check are redundant: If the Y(i,1)>=1 check is FALSE, you do not have to check for Y(i,1)<1 again:
Y = random('unif',0.01,2,100,1);
c = zeros(100, 3); % Pre-allocation!!!
for i = 1:100
if Y(i,1) >= 1
c(i,1)=1;
% c(i,2)=0; % Set already
elseif Y(i,1) >= 0.1
c(i,1)=1;
c(i,2)=0.5;
elseif Y(i,1) >= 0.01
c(i,1)=1;
c(i,2)=1;
else
% c(i,1)=0; % Set already
c(i,2)=1;
end
end
c(i,3) is set to 0 in all cases. Then it is cheaper to set the default value in the pre-allocation accordingly.

Categorías

Más información sobre Creating, Deleting, and Querying Graphics Objects en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by