Using 3D plot to model orbit.
3 views (last 30 days)
Show older comments
Having problems with getting this right. Want to have the straight line equation move up the middle of the rising eliptical shape. If you run the code now the line goes nowhere near up the middle of the elipse. Just trying to code a basic orbit around a planet and if anyone has any suggestions to make this a little better that would be great!
Got this idea from MATLAB youtube video about 3D plots and wanted to explore it a little more.
t = linspace(0, 8*pi, 100);
x = 6*cos(t);
y = 4*sin(t);
z = t;
z2 = t/3;
x2 = t;
y2 = t;
for k=1:length(t)
clf
t_k = t(k);
x_k = x(k);
y_k = y(k);
z_k = z(k);
x2_k = x2(k);
y2_k = y2(k);
z2_k = z2(k);
plot3(x_k, y_k, z_k, 'bo', 'LineWidth', 2, 'MarkerSize', 16)
hold on
plot3(x, y, z, 'b-', 'LineWidth', 2)
hold on
plot3(x2_k, y2_k, z2_k, 'bo', 'LineWidth', 2, 'MarkerSize', 16)
hold on
plot3(x2, y2, z2, 'b-', 'LineWidth', 2)
grid on
xlabel('x')
ylabel('y')
zlabel('z')
title('Planetary Orbit')
drawnow
end
0 Comments
Answers (1)
Yash
on 21 Jul 2025
The straight line modeled in your code is a line going diagonally through space and not through the center of the ellipse. The spiral rises along the z-axis as 't' increases. You can replace the definition of the line with:
x2 = zeros(size(t));
y2 = zeros(size(t));
z2 = t;
This will plot a straight line along the z-axis, up the center of the ellipse. Below is the updated code:
t = linspace(0, 8*pi, 100);
x = 6*cos(t);
y = 4*sin(t);
z = t;
x2 = zeros(size(t));
y2 = zeros(size(t));
z2 = t;
for k=1:length(t)
clf
t_k = t(k);
x_k = x(k);
y_k = y(k);
z_k = z(k);
x2_k = x2(k);
y2_k = y2(k);
z2_k = z2(k);
plot3(x_k, y_k, z_k, 'bo', 'LineWidth', 2, 'MarkerSize', 16)
hold on
plot3(x, y, z, 'b-', 'LineWidth', 2)
hold on
plot3(x2_k, y2_k, z2_k, 'ro', 'LineWidth', 2, 'MarkerSize', 16)
hold on
plot3(x2, y2, z2, 'r-', 'LineWidth', 2)
grid on
xlabel('x')
ylabel('y')
zlabel('z')
title('Planetary Orbit')
axis equal
drawnow
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!