MATLAB: How to plot the interpolation of a set of points whose x coordinates range from [-pi, pi] without having the line to go back and forth the figure (which has the axis from – pi to pi)

-pi to pi.MATLABperiodicplot

Basically I'm trying to do the ground track of a satellite and I want to plot in real time (using drawnow) the interpolation of a set of calculated points representing the projection of the satellite's position in space on Earth. The longitude axis goes from -180 to 180 degrees. If I make matlab simply run:
for i = 2 : n-1 % n is the number of points

plot(longitude(i-1: i+1), latitude(i-1: i+1), 'r'); hold on; drawnow
end
the plot will be covered with almost horizontal lines since the satellite will reach a point close to longitude = 180 and then it will reappear close to longitude = -180, on the other side of the figure. With the code I wrote before matlab will connect the former point with the latter with a line that goes all accross the figure from right to left. I've actually solved this problem in most cases writing a series of "if"s but I'd like to know if there is a way to avoid this problem without complicating the code with all of those "if"s. I'm asking this because of course i'd like to avoid simply plotting the points like this:
for i = 2 : n-1 % n is the number of points
plot(longitude(i), latitude(i), 'r.'); hold on; drawnow
end
Yes, it woud solve the problem but it's uglier 😀

Best Answer

how about something like that:
figure(1);
hold on;
currIdx = 1;
for i = [find(abs(diff(longitude')) > 10), length(longitude)]
idx = currIdx:i;
if length(idx) < 2
style = '.r';
else
style = 'r';
end
plot(longitude(idx), latitude(idx), style);
currIdx = i+1;
end
It finds the indices where theres a big jump in the longitude, and cuts the plot there