if statement in a function

3 visualizaciones (últimos 30 días)
Maja Zdulska
Maja Zdulska el 29 de En. de 2021
Comentada: Maja Zdulska el 30 de En. de 2021
Hi everyone,
I'm trying to create a function that will calculate wind direction from wind speed vectors u and v. I have the code presented below. However, it seems that the if loop is not taken into account (function outputs directions in the -180 to 180 degrees range). What am I doing wrong?
Thanks in advance.
function calc_wind_dir(filename)
%load data
data = readtable(filename);
%define wind variables, u is E-W component, v is N-S component
u = data{:,11};
v = data{:,12};
% The following code line gives wind angle relative to N, where:
% u is the W-E velocity (positive if the wind is blowing to the E from the W)
% v is the N-S velocity component (positive when blowing from S to N).
% j is sqrt(-1)
raw_direction=180*angle(v + j*u)/pi;
%The above measures where the wind is going rather than coming.
%In other words, the line of code above gives:
%E wind = Direction -90 dgrees
%W wind = Direction 90 dgrees
%S wind = Direction 0 degrees
%N wind = Direction 180 degrees
%The following will change the sign and indicate where the wind is coming from instead
direction=-180*angle(v + j*u)/pi;
%Here angles are measured positively (clockwise) and negatively (anti-clockwise) from N.
%(i.e. no angles will be bigger than +/-180 degrees).
%Below makes the wind more conventional (0-360 degrees).
if direction < 0
direction = direction + 360;
end
  2 comentarios
dpb
dpb el 29 de En. de 2021
if is True iff all elements in the quantity are true; not what is wanted here.
Use logical indexing -- replace the if block with
direction(direction<0)=direction(direction<0) + 360;
You may want to save the logical vector for reuse as
isLZ=(direction<0);
direction(isLZ)=direction(isLZ)+360;
I'm not sure if the JIT optimizer is clever enough to recognize the common expression and avoid the recalculation or not.
Maja Zdulska
Maja Zdulska el 30 de En. de 2021
Thanks a lot!

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by