How can I represent points and lines in 3 dimensions?

1 view (last 30 days)
ox=0; oy =0; oz=0;
x1=0; y1 =0; z1=0;
x2=0; y2 =0; z2=0;
x3=2; y3 =0.6; z3=0;
x4=2; y4 =0.3; z4=0;
x5=2; y5 =0.3; z5=-0.7;
x6=2; y6 =0.3; z6=-0.7;
hold on;
x = [ox x1 x2 x3 x4 x5 x6]; % a matrix of dots
y = [oy y1 y2 y3 y4 y5 y6];
z = [oz z1 z2 z3 z4 z5 z6];
plot3(x,y,z,'ok') %plot points on a graph
plot3([ox, x1],[oy, y1],[oz, z1], 'r') %to connect dots and lines
plot3([x1, x2],[y1, y2],[z1, z2], 'g')
plot3([x2, x3],[y2, y3],[z2, z3], 'b')
plot3([x3, x4],[y3, y4],[z3, z4], 'c')
plot3([x4, x5],[y4, y5],[z4, z5], 'm')
plot3([x5, x6],[y5, y6],[z5, z6], 'y')
max_L = 3;
axis([-max_L max_L -max_L max_L -max_L max_L]);
If I draw like this, it will appear in 2D instead of 3D. How can I represent it in 3D?

Accepted Answer

DGM on 16 May 2022
Edited: DGM on 16 May 2022
Either move the hold on statement after the first call to plot3(), or issue a
command after plotting.
Creating a pile of named variables only leads to problems. Imagine if you wanted to do this with 100 points. With the following example, the code doesn't have to be scaled with the number of points. All you need to do is generate a new colormap of the appropriate length.
% just the points
x = [0 0 0 2 2 2 2];
y = [0 0 0 0.6 0.3 0.3 0.3];
z = [0 0 0 0 0 -0.7 -0.7];
plot3(x,y,z,'ok') %plot points on a graph
hold on;
% rearrange into a series of segments
x = repelem(x,1,2);
x = reshape(x(2:end-1),2,[]).';
y = repelem(y,1,2);
y = reshape(y(2:end-1),2,[]).';
z = repelem(z,1,2);
z = reshape(z(2:end-1),2,[]).';
plot3(x,y,z) %to connect dots and lines
% apply whatever colormap you want to the series of line segments
cmap = hsv(6);
cmap = cmap([1 3 5 4 6 2],:); % to get the same order you used
max_L = 3;
axis([-max_L max_L -max_L max_L -max_L max_L]);

Sign in to comment.

More Answers (1)

KSSV on 16 May 2022
It is in 3D, you need to change the view.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!