if statement problem
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Oleg Komarov
2011-8-26
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
更多回答(2 个)
Sean de Wolski
2011-8-26
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 个评论
Jan
2011-8-26
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating, Deleting, and Querying Graphics Objects 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!