If function in matlab

9 Ansichten (letzte 30 Tage)
Mohana
Mohana am 20 Feb. 2019
Beantwortet: Mohana am 21 Feb. 2019
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 Kommentare
Omer Yasin Birey
Omer Yasin Birey am 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.
Mohana
Mohana am 21 Feb. 2019
Bearbeitet: Mohana am 21 Feb. 2019
What i meant is,
if M16 is less than 292.5 and greater than 247.5 then it is SW.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Stephen23
Stephen23 am 20 Feb. 2019
Bearbeitet: Stephen23 am 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:
  2 Kommentare
Mohana
Mohana am 21 Feb. 2019
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 am 21 Feb. 2019
@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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Mohana
Mohana am 21 Feb. 2019
Thanks will take care.

Community Treasure Hunt

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

Start Hunting!

Translated by