MATLAB: How to insert legend in plot after a for cycle

3d plotslegend

I have a problem with the insertion of legend in a 3D plot in matlab. I have a list of data, in particular I have a nx3 matrix filled with data to plot and I want to separate these data by means of a discriminant. In my case the discriminant is time, so if i-th data is before the discriminant time it will be plotted in blue color, otherwise in red color. The code is
figure(1)
plot3(ra(1),dec(1),Time2plot(1),'*','Color','r', 'DisplayName', 'observation day');
hold on;
plot3(ra(end),dec(end),Time2plot(end),'*','Color','b','DisplayName', 'next day');
legend show;
for i = 1:length(Time2plot)
if timeofday(Time2plot(i)) > B(1) && timeofday(Time2plot(i)) < B(2)
hold on;
plot3(ra(i),dec(i),Time2plot(i),'*','Color', 'b');
else
hold on;
plot3(ra(i),dec(i),Time2plot(i),'*','Color','r');
end
end
hold on;
title(['RA Dec in 3D ', date(1,1)]);
xlabel('RA');
ylabel('Dec');
zlabel('Time');
ztickformat('HH:mm:ss');
grid on;
where B is discriminant time.
The result is
pp.jpg
The issue is that I'd like only two line in legend: 'next day' and 'observation day' and not all data. Someone can help me?

Best Answer

I cannot run your code, so here is a prototype you can adapt:
figure
hold on
for i = 1:10
hpb = plot3(rand, rand, rand, '*b','DisplayName', 'next day');
hpr = plot3(rand, rand, rand, '*r', 'DisplayName', 'observation day');
end
hold off
legend([hpb(1),hpr(1)])
grid on
view(-35,35)
producing:
1How to insert legend in plot after a for cycle - 2020 01 11.png
The key to doing what you want is to return handles from the plot3 calls, then use only the first of each in the legend call.