如何矢量化四行MATLAB?

问题描述 投票:0回答:3

是否可以通过矢量化将以下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
matlab range vectorization angle
3个回答
1
投票

我的印象是你可以更进一步

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

1
投票

更安全的方法是使用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;

0
投票

对不起,几分钟后我才发现自己......

temp1(temp1>=270)=temp1(temp1>=270)-360;
temp1(temp1<=-90)=temp1(temp1<=-90)+360;
© www.soinside.com 2019 - 2024. All rights reserved.