If function in matlab

4 ビュー (過去 30 日間)
Mohana
Mohana 2019 年 2 月 20 日
回答済み: Mohana 2019 年 2 月 21 日
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.
Regards and thanks in advance
  2 件のコメント
Omer Yasin Birey
Omer Yasin Birey 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 2019 年 2 月 21 日
編集済み: Mohana 2019 年 2 月 21 日
What i meant is,
if M16 is less than 292.5 and greater than 247.5 then it is SW.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2019 年 2 月 20 日
編集済み: Stephen23 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:
  2 件のコメント
Mohana
Mohana 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.
Stephen23
Stephen23 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.

サインインしてコメントする。

その他の回答 (1 件)

Mohana
Mohana 2019 年 2 月 21 日
Thanks will take care.

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by