If function in matlab
9 views (last 30 days)
Show older comments
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 Comments
Omer Yasin Birey
on 20 Feb 2019
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.
Accepted Answer
Stephen23
on 20 Feb 2019
Edited: Stephen23
on 20 Feb 2019
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:
More Answers (1)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!