Clear Filters
Clear Filters

Plotting Cylinder Surface Using fill3

6 views (last 30 days)
I am attempting to plot a cylinder (or any abitrary) surface using the fill3 or patch function.
MATLAB, however, does not produce the cylinder surface using the minmal working example below, unless the angle theta is restricted to less than pi.
Any help explaining this issue and finding a solution is greatly appreciated!
figure()
theta = 0:0.5:2*pi;
xs = [cos(theta) flip(cos(theta))];
ys = [sin(theta) flip(sin(theta))];
fill3(xs, ys, [zeros(size(theta)) ones(size(theta))], 'k', 'FaceAlpha', 0.2)

Accepted Answer

Star Strider
Star Strider on 24 May 2024
It is easier to use the surf function for this —
% figure()
% theta = 0:0.5:2*pi;
theta = linspace(0, 2*pi, 11);
xs = [cos(theta); flip(sin(theta))];
ys = [sin(theta); flip(cos(theta))];
figure
surf(xs, ys, [zeros(size(theta)); ones(size(theta))], 'FaceAlpha', 0.2)
view(-27,30)
figure
surf([cos(theta); cos(theta)].', [sin(theta); sin(theta)].', [ones(size(theta)); zeros(size(theta))].', 'FaceColor','c', 'FaceAlpha',0.5)
view(-27,30)
It can probably be done with patch, however I have always used surf for these sorts of problems.
.
  2 Comments
Florian Radack
Florian Radack on 27 May 2024
Thanks for the answer, this solution works. However, it does not explain the behaviour of the surf or fill3 functions.
Star Strider
Star Strider on 27 May 2024
As always, my pleasure!
I can almost always get patch to work in 2-D plots, however getting it to work in 3-D plots requires some sort of magic that I’ve not yet discovered.
Actually, I just now figured out how to get patch to work here, however it requires a loop for each segment of the circle —
theta = linspace(0, 2*pi, 11);
xs = cos(theta);
ys = sin(theta);
figure
hold on
for k = 1: numel(xs)-1
patch([xs([k k+1]) flip(xs([k k+1]))], [ys([k k+1]) flip(ys([k k+1]))], [0 0 1 1], 'g', 'FaceAlpha',0.5)
end
hold off
grid on
view(-27,30)
This is similar to the approach with the entire circle, however for whatever reason (perhaps that the beginnings and ends are essentially the same point), it fails with the complete circle.
It is then straightforward to add the top an bottom surfaces, closing the cylinder —
figure
hold on
for k = 1: numel(xs)-1
patch([xs([k k+1]) flip(xs([k k+1]))], [ys([k k+1]) flip(ys([k k+1]))], [0 0 1 1], 'g', 'FaceAlpha',0.5)
end
patch(xs, ys, zeros(size(theta)), 'r', 'FaceAlpha',0.75)
patch(xs, ys, ones(size(theta)), 'b', 'FaceAlpha',0.5)
hold off
grid on
view(-27,30)
This seems to ‘sort of’ solve it, without solving the mystery of the complete circle failing to work with essentially the same sort of approach.
.

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!