如何向量化四行MATLAB?

How to vectorise four lines of MATLAB?

是否可以通过矢量化将以下MATLAB代码改写成一行?

for ii=1:length(temp1)
    if temp1(ii)>=270; temp1(ii)=temp1(ii)-360;end
    if temp1(ii)<=-90; temp1(ii)=temp1(ii)+360;end
end

抱歉,几分钟后我才想通...

temp1(temp1>=270)=temp1(temp1>=270)-360;
temp1(temp1<=-90)=temp1(temp1<=-90)+360;

我觉得你可以更进一步

temp1 = temp1 + 360 * (temp1 >= 270) - 360 * (temp1 <= -90)

更安全的方法是使用 mod,因为它更稳健并且可以正确处理超出 th < -450th > 630 范围的角度:

temp1 = mod(temp1,360); temp1(temp1 >= 270) = temp1(temp1 >= 270)-360;

你也可以从函数wrapTo180:

中获取灵感
function lon = wrapTo180(lon)
%wrapTo180 Wrap angle in degrees to [-180 180]
%
%   lonWrapped = wrapTo180(LON) wraps angles in LON, in degrees, to the
%   interval [-180 180] such that 180 maps to 180 and -180 maps to -180.
%   (In general, odd, positive multiples of 180 map to 180 and odd,
%   negative multiples of 180 map to -180.)
%
%   See also wrapTo360, wrapTo2Pi, wrapToPi.

% Copyright 2007-2008 The MathWorks, Inc.

q = (lon < -180) | (180 < lon);
lon(q) = wrapTo360(lon(q) + 180) - 180;