if else statement problems

조회 수: 8 (최근 30일)
Mohamad Yazid
Mohamad Yazid 2017년 9월 27일
편집: Stephen23 2017년 9월 27일
I want to create a new data based on this rules:
1) if x = 0 AND y value within 52-336, then value of z will be 0. the value of Z will be 1 if y is less than 52 or more than 336.
2) if x = 1 AND y value within 38-176, then value of z will be 0. the value of Z will be 1 if y is less than 38 or more than 176.
This is my code:
x = [0,0,0,0,1,0,1,0,0,1];
y = [60,264,400,89,170,119,30,60,167,180];
for i = 10
if x (:,i) == 0 && y (:,i) >=52 && y (:,i) <=336
z (:,i) = 0;
elseif x (:,i) == 0 && y (:,i) <52
z(:,i) = 1;
elseif x (:,i) == 0 && y (:,i) >336
z(:,i) = 1;
elseif x (:,i) == 1 && y (:,i) >=38 && y (:,i) <=176
z (:,i) = 0;
else
z(:,i) = 1;
end
end
i'm expecting z value will like this [0,0,1,0,0,0,1,0,0,1] but instead i got this value [0,0,0,0,0,0,0,0,0,1]
Can somebody help me to identify what is wrong with this code.
Thank You

채택된 답변

Stephen23
Stephen23 2017년 9월 27일
편집: Stephen23 2017년 9월 27일
The problem is very simple: your code only loops over one value:
for i = 10
Whereas you probably wanted to loop over ten values:
for i = 1:10
Here is a much simpler solution:
>> x = [0,0,0,0,1,0,1,0,0,1];
>> y = [60,264,400,89,170,119,30,60,167,180];
>> z = (x==0 & (y<52 | y>336)) | (x==1 & (y<38 | y>176))
z =
0 0 1 0 0 0 1 0 0 1
>>

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by