plot and create the intersection of 2 perpendicular cylinders in matlab

main.m
% Define the radius and height for both cylinders
radius1 = 1;
height1 = 4;
radius2 = 1;
height2 = 4;

% Define the axis for plotting
theta = linspace(0, 2*pi, 100); % angles from 0 to 2*pi
z1 = linspace(0, height1, 100); % heights for the first cylinder
z2 = linspace(0, height2, 100); % heights for the second cylinder

% Create the first cylinder
X1 = radius1 * cos(theta);
Y1 = radius1 * sin(theta);
Z1 = z1;
[X1_grid, Y1_grid, Z1_grid] = meshgrid(X1, Y1, Z1);

% Create the second cylinder
X2 = radius2 * cos(theta);
Y2 = radius2 * sin(theta);
Z2 = z2;
[X2_grid, Y2_grid, Z2_grid] = meshgrid(X2, Y2, Z2);

% Plot the first cylinder
figure;
surf(X1_grid, Y1_grid, Z1_grid, 'FaceAlpha', 0.5, 'FaceColor', 'b', 'EdgeColor', 'none');
hold on;

% Plot the second cylinder
surf(X2_grid, Y2_grid, Z2_grid, 'FaceAlpha', 0.5, 'FaceColor', 'r', 'EdgeColor', 'none');

% Calculate the intersection between the two cylinders
intersectionX = [];
intersectionY = [];
intersectionZ = [];

for i = 1:size(X1_grid, 1)
    for j = 1:size(X1_grid, 2)
        if sqrt(X1_grid(i,j)^2 + Y1_grid(i,j)^2) == radius1 && sqrt(X2_grid(i,j)^2 + Y2_grid(i,j)^2) == radius2
            intersectionX = [intersectionX, X1_grid(i, j)];
            intersectionY = [intersectionY, Y1_grid(i, j)];
            intersectionZ = [intersectionZ, Z1_grid(i, j)];
        end
    end
end

% Plot the intersection points
plot3(intersectionX, intersectionY, intersectionZ, 'ko', 'MarkerFaceColor', 'g');

1468 chars
50 lines

related categories

gistlibby LogSnag