### Translated by

このページのコンテンツは英語から自動翻訳されています。自動翻訳をオフにする場合は「<a class="turn_off_mt" href="#">ここ</a>」をクリックしてください。

## If function in matlab

Mohana

### Mohana (view profile)

さんによって質問されました 2019 年 2 月 20 日

### Mohana (view profile)

さんによって 回答されました 2019 年 2 月 21 日
Stephen Cobeldick

### Stephen Cobeldick (view profile)

さんの 回答が採用されました
I am using the following if function / formula in excel.
=IF(A1>292.5,"NW", IF(A1>247.5,"W", IF(A1>202.5,"SW",IF(A1>157.5,"S",IF(A1>112.5,"SE",IF(A1>67.5,"E",IF(A1>22.5,"NE")))))))
I have written the following code:
for k=1:I
if M16>292.5
fprintf('SW\n')
elseif (M16<292.5>247.5)
fprintf('W\n')
elseif (M16<247.5>202.5)
fprintf('SW\n')
elseif (M16<202.5>157.5)
fprintf('S\n')
elseif (M16<157.5>112.5)
fprintf('SE\n')
elseif (M16<112.5>67.5)
fprintf('E\n')
elseif (M16<67.5>22.5)
fprintf('NE\n')
elseif (M16<22.5>0)
fprintf('N\n')
else
'invalid'
end
end
I am not getting proper result. Can anyone help.

Omer Yasin Birey

### Omer Yasin Birey (view profile)

2019 年 2 月 20 日
What is this double comparisons. Such as
(M16<292.5>247.5)
Obviously 292.5 is greater than 247.5, I don't understand why are you comparing them. And regardless of the correctness of the comparison, I believe each line that has these kind of comparisons will return 0. Meaning that the code will never explore inside the if's.
Mohana

### Mohana (view profile)

2019 年 2 月 21 日
What i meant is,
if M16 is less than 292.5 and greater than 247.5 then it is SW.

サインイン to comment.

## 2 件の回答

2019 年 2 月 20 日

### Stephen Cobeldick (view profile)

2019 年 2 月 20 日
採用された回答

MATLAB is not Excel, and it is better to write code specifically for MATLAB:
>> C = {'N','NE','E','SE','S','SW','W','NW'};
>> fun = @(a) C{1+fix(mod(a+360/16,360)/45)};
>> fun(0)
ans = N
>> fun(-22)
ans = N
>> fun(-90)
ans = W
>> fun(90)
ans = E
>> fun(60)
ans = NE
PS: your code does not work because you invented this syntax:
M16<292.5>247.5
i.e.
A<B>C
which is equivalent to:
(A<B)>C
Because A<B returns either 0 or 1, this is equivalent to either of these:
(1)>C
(0)>C
and this will always be false for any C>=1 (e.g. all of the values that you used).
Rather than inventing syntaxes that do not work, it is more effective to read the MATLAB documentation:

Mohana

### Mohana (view profile)

2019 年 2 月 21 日
Thanks for your kind reply, can this code be used for n values, reading the input from an input file, rather than feeding every time the input value.
Stephen Cobeldick

### Stephen Cobeldick (view profile)

2019 年 2 月 21 日
@Mohana: you can vectorize the code I gave you simply by returning a cell array instead of extracting the cell array contents:
C(1+fix(mod(a+360/16,360)/45));
^ ^ return a cell array
This will also work with a string array.

サインイン to comment.

### Mohana (view profile)

2019 年 2 月 21 日

Thanks will take care.

#### 0 件のコメント

サインイン to comment.

Translated by