TyanTowers
TyanTowers

Reputation: 160

Plotting many unconnected lines in MATLAB

I need to plot a lot of unconnected lines in MATLAB. This code will do it using a for loop:

x = 1:5;
y = 10:-2:2;
figure;
hold on;
for ii = 1:5
    plot([0,x(ii)],[0,y(ii)],'b-');
end

Is it possible to do the same thing without using a for loop?

Use case: I am trying to visualize a tree and there are many lines to be drawn. I would like to precalculate the end points of all the lines and call plot or equivalent once. This is what I am doing with scatter to show the nodes of the tree.

Upvotes: 4

Views: 605

Answers (2)

obchardon
obchardon

Reputation: 10792

Another solution:

plot([zeros(1,length(x));x],[zeros(1,length(x));y],'r-')

Upvotes: 2

Matt
Matt

Reputation: 13933

You can make use of NaN to disconnect lines when plotting. Therefore, you can concatenate your x and y values with an NaN-vector of the same length and then reshape it in order to have an NaN to disconnect the lines in between the individual segments.

To make the code universally applicable, we introduce xo and yo to be the coordinates of the origin. Now, the points to be plotted can be calculated as follows:

xp = reshape([ones(size(x))*xo;x;NaN(size(x))],1,[]);
yp = reshape([ones(size(y))*yo;y;NaN(size(y))],1,[]);

The xp-vector looks like this now:

0   1   NaN    0   2   NaN    0   3   NaN    0   4   NaN    0   5   NaN
└ origin           └ end point of segment 2           └ to disconnect lines

The whole code to produce the same result as in your question is the following:

x = 1:5;
y = 10:-2:2;

figure;
xo = 0;     % x-coordinate of origin
yo = 0;     % y-coordinate of origin
xp = reshape([ones(size(x))*xo;x;NaN(size(x))],1,[]);
yp = reshape([ones(size(y))*yo;y;NaN(size(y))],1,[]);
plot(xp,yp,'b-');

Upvotes: 3

Related Questions