简体   繁体   中英

How to vectorise four lines of MATLAB?

Is it possible to rewrite the following MATLAB code into one single line by vectorization?

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 + 360 * (temp1 >= 270) - 360 * (temp1 <= -90)

A safer way would be to use mod , because this is more robust and can handle correctly angles that are outside the range of th < -450 or th > 630 :

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

You can also take inspiration from the function 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;

Sorry, I just figured out myself after some minutes...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM