How to plot all the six planes of a cube/rectangular prism around a 3D plot using MATLAB function 'plot3'?

I'm using the MATLAB function `plot3` to create a 3D plot, but it's only displaying the three coordinate axes. I would like to enclose the 3D plot within a cube or rectangular prism.
With the documentation example - Plot Multiple Lines Using Matrices of the MATLAB function plot3, how can I enclose the plot within a cube or rectangular prism?

% matrix X contains three rows of x-coordinate
>> t = 0:pi/500:pi;
>> X(1,:) = sin(t).*cos(10*t);
>> X(2,:) = sin(t).*cos(12*t);
>> X(3,:) = sin(t).*cos(20*t);

% matrix Y contains three rows of y-coordinate
>> Y(1,:) = sin(t).*sin(10*t);
>> Y(2,:) = sin(t).*sin(12*t);
>> Y(3,:) = sin(t).*sin(20*t);

% matrix Z contains the z-coordinates for all three sets
>> Z = cos(t);

% Plot all three sets of coordinates on the same set of axes.
>> figure
>> plot3(X,Y,Z)

>> xlabel('X-axis');
>> ylabel('Y-axis');
>> zlabel('Z-axis');
>> title('3D Line Plot');

% Enable grid for better visualization
>> grid on;

which results in the figure below:

 Réponse acceptée

The MATLAB function 'plot3' itself allows you to highlight only the three coordinate axes (x, y, z) and at best the corresponding three planes.
However, to display the entire cube (or rectangular prism) on the example (i.e., Plot Multiple Lines Using Matrices from the documentation of the MATLAB function plot3) from the query, you'll need to add three additional planes to the plot. Using the same example, add the following code at the end of the code mentioned in the query:
% Turn on the box to highlight existing edges of the plot
>> box on;
% Get current axis limits
>> xlim = get(gca, 'XLim');
>> ylim = get(gca, 'YLim');
>> zlim = get(gca, 'ZLim');
% Define the vertices of the cube
>> vertices = [
xlim(1), ylim(1), zlim(1);
xlim(2), ylim(1), zlim(1);
xlim(2), ylim(2), zlim(1);
xlim(1), ylim(2), zlim(1);
xlim(1), ylim(1), zlim(2);
xlim(2), ylim(1), zlim(2);
xlim(2), ylim(2), zlim(2);
xlim(1), ylim(2), zlim(2);
];
% Define the edges of the cube
>> edges = [
1, 2; 2, 3; 3, 4; 4, 1; % Bottom face
5, 6; 6, 7; 7, 8; 8, 5; % Top face
1, 5; 2, 6; 3, 7; 4, 8; % Vertical edges
];
% Plot the cube edges
>> hold on;
>> for i = 1:size(edges, 1)
>> v1 = vertices(edges(i, 1), :);
>> v2 = vertices(edges(i, 2), :);
>> plot3([v1(1), v2(1)], [v1(2), v2(2)], [v1(3), v2(3)], 'k-');
>> end
>> hold off;
and the resultant output figure will be as below:

Plus de réponses (0)

Produits

Version

R2024b

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by