fractal figure in matlab

Here's an example code for drawing a Sierpinski triangle in MATLAB using recursion:

main.m
function sierpinski(x, y, len, depth)
% x and y are the coordinates of the bottom left corner
% len is the length of the side of the triangle
% depth is the recursion depth

if depth == 0
    % Base case
    triangle(x, y, len);
else
    % Recursive case
    sierpinski(x, y, len/2, depth-1);
    sierpinski(x+len/2, y, len/2, depth-1);
    sierpinski(x+len/4, y+len*sqrt(3)/4, len/2, depth-1);
end
end

function triangle(x, y, len)
% Helper function to draw a triangle

x = [x, x+len/2, x-len/2];
y = [y, y+len*sqrt(3)/2, y+len*sqrt(3)/2];
fill(x, y, 'r');
drawnow;
end
571 chars
25 lines

Here's how you can call the sierpinski function:

main.m
sierpinski(0, 0, 10, 4);
25 chars
2 lines

This will draw a Sierpinski triangle with side length 10 and recursion depth 4. You can adjust these parameters to get a different shape or level of detail.

gistlibby LogSnag