divide a triangle with vertices (-1,1) (-1, 0) (0, 1) into n^2 triangles in matlab

To divide a triangle into n^2 smaller triangles, we can uniformly divide the base and height of the triangle into n equal parts, and then draw lines connecting the corresponding points on the base and height to create the smaller triangles.

Here's the code in Matlab:

main.m
% Define the vertices of the triangle
A = [-1 1];
B = [-1 0];
C = [0 1];

% Define the number of divisions
n = 5;

% Calculate the coordinates of the lines connecting the divisions
x_lines = linspace(A(1), B(1), n+1);
y_lines = linspace(C(2), A(2), n+1);

% Initialize the triangles matrix
triangles = zeros(n*n, 3);

% Loop through each square and create two triangles
index = 1;
for i = 1:n
    for j = 1:n
        % Define the vertices of the two triangles
        v1 = [x_lines(i) y_lines(j)];
        v2 = [x_lines(i+1) y_lines(j)];
        v3 = [x_lines(i) y_lines(j+1)];
        v4 = [x_lines(i+1) y_lines(j+1)];
        
        % Add the two triangles to the triangles matrix
        triangles(index, :) = [v1 v2 v3];
        triangles(index+1, :) = [v4 v2 v3];
        
        % Increment the index
        index = index + 2;
    end
end

% Plot the original triangle and the smaller triangles
patch([A(1) B(1) C(1)], [A(2) B(2) C(2)], 'b');
hold on
for i = 1:size(triangles, 1)
    patch(triangles(i, 1:2:end), triangles(i, 2:2:end), 'r');
end
axis equal
hold off
1076 chars
43 lines

This code defines the vertices of the original triangle and the number of divisions. It then calculates the coordinates of the lines connecting the divisions, and uses a nested loop to create two smaller triangles for each square. The vertices of these triangles are added to the triangles matrix. Finally, the original triangle and the smaller triangles are plotted using patch functions. The axis equal command ensures that the plot is scaled equally in both directions.

gistlibby LogSnag