If function in matlab

조회 수: 9 (최근 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 CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by