if statement in a function

4 次查看(过去 30 天)
Maja Zdulska
Maja Zdulska 2021-1-29
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 个评论
dpb
dpb 2021-1-29
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.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by