plot an christam tree in matlab

To plot a Christmas tree in Matlab, we can use the plot and fill functions to draw triangles with different colors and heights. Here is a sample code to plot a Christmas tree:

main.m
% Set the size of the plot window
figure('Color', [0.1 0.1 0.1], 'Position', [100 100 800 800]);

% Define the parameters of the tree
n = 10; % Number of levels
h = 0.1; % Height of each level
w = 0.5; % Width of the base of the tree
colors = winter(n+1); % Colors for each level

% Draw the levels of the tree
for i = 1:n
    % Define the vertices of the triangle for the level
    x = [0, w/2^(i-1), -w/2^(i-1)];
    y = [(i-1)*h, i*h, i*h];
    
    % Plot the triangle with the appropriate color
    fill(x, y, colors(i,:), 'EdgeColor', 'none');
end

% Add a star on top of the tree
x = [-0.1, 0, 0.1];
y = [n*h+h/4, n*h+h/2, n*h+h/4];
fill(x, y, 'y', 'EdgeColor', 'none');

% Add some ornaments on the tree
hold on;
x = [-0.4, -0.3, -0.35, -0.4, -0.45, -0.4];
y = [1.8, 1.9, 1.95, 2, 1.95, 1.9];
fill(x, y, 'r', 'EdgeColor', 'none');
x = [0.3, 0.4, 0.35, 0.3, 0.25, 0.3];
y = [1.6, 1.7, 1.75, 1.8, 1.75, 1.7];
fill(x, y, 'b', 'EdgeColor', 'none');
x = [-0.35, -0.25, -0.3, -0.35];
y = [1.5, 1.4, 1.45, 1.5];
fill(x, y, 'g', 'EdgeColor', 'none');
x = [0.25, 0.35, 0.3, 0.25];
y = [1.3, 1.4, 1.35, 1.3];
fill(x, y, 'm', 'EdgeColor', 'none');
hold off;

% Set the axis limits and remove the axis ticks and labels
xlim([-w/2^n, w/2^n]);
ylim([0, n*h+h/2]);
set(gca, 'XTick', []);
set(gca, 'YTick', []);
1304 chars
46 lines

When you run this code, it will generate a plot with a Christmas tree, a star on top, and some ornaments. You can customize the parameters of the tree, such as the number of levels, height, and width, as well as the colors of the levels and ornaments.

gistlibby LogSnag