if statement problem
16 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Oleg Komarov
le 26 Août 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
Plus de réponses (2)
Sean de Wolski
le 26 Août 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
0 commentaires
Jan
le 26 Août 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.
Voir également
Catégories
En savoir plus sur Creating, Deleting, and Querying Graphics Objects dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!