if else statement problems

8 次查看(过去 30 天)
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