if else statement problems

5 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by