if statement problem
조회 수: 12 (최근 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!