christmas tree in matlab

To create a Christmas tree in MATLAB, you can use the plot function along with some basic geometry and creativity. Here's an example of how you can create a Christmas tree using MATLAB:

main.m
% Set the tree parameters
treeLevels = 6;     % Number of levels in the tree
branchWidth = 0.4;  % Width of each branch
treeHeight = 1.8;   % Height of the tree

% Create the tree trunk
trunkWidth = 0.2;   % Width of the trunk
trunkHeight = 0.3;  % Height of the trunk

trunkX = [0 trunkWidth trunkWidth 0 0];
trunkY = [0 0 trunkHeight trunkHeight 0];

% Plot the tree trunk
figure;
plot(trunkX, trunkY, 'LineWidth', 2, 'Color', 'brown');
hold on;

% Create the tree branches
for level = 1:treeLevels
    branchHeight = treeHeight / treeLevels;
    branchWidth = branchWidth + 0.1;  % Increase branch width with each level
    
    % Calculate the x-coordinates of the branches
    branchX = [-(branchWidth/2) (branchWidth/2) (branchWidth/2) -(branchWidth/2) -(branchWidth/2)];
    
    % Calculate the y-coordinates of the branches
    branchY = [(level-1)*branchHeight level*branchHeight level*branchHeight (level-1)*branchHeight (level-1)*branchHeight];
    
    % Plot the tree branches
    plot(branchX, branchY, 'LineWidth', 2, 'Color', 'green');
end

% Set axis limits and aspect ratio
axis([-1.5 1.5 0 2]);
axis equal;

% Add decorations (optional)
starSize = 0.1;  % Size of the star on top of the tree

% Plot the star on top of the tree
plot(0, 2, 'p', 'MarkerSize', starSize*100, 'MarkerEdgeColor', 'yellow', 'LineWidth', 2);

% Add red ornaments to the tree
for level = 1:treeLevels
    % Calculate the number of ornaments for the current level
    numOrnaments = level + 1;
    
    % Generate random x-coordinates for the ornaments
    xOrnaments = (-0.9 + rand(1, numOrnaments) * 1.8) * (branchWidth/2);
    
    % Calculate the y-coordinate of the ornaments
    yOrnaments = level * branchHeight - branchHeight/2;
    
    % Plot the ornaments
    scatter(xOrnaments, yOrnaments, 50, 'red', 'filled');
end

% Add a tree trunk base (optional)
baseWidth = 1.2;  % Width of the tree trunk base
baseHeight = 0.1; % Height of the tree trunk base

baseX = [-baseWidth/2 baseWidth/2 baseWidth/2 -baseWidth/2 -baseWidth/2];
baseY = [0 0 -baseHeight -baseHeight 0];

% Plot the tree trunk base
fill(baseX, baseY, 'brown');

% Remove axis ticks and labels
set(gca, 'xtick', []);
set(gca, 'ytick', []);

% Hide box around the plot
box off;

% Set color to white for background
set(gcf, 'color', 'w');
2307 chars
77 lines

This code will generate a MATLAB figure that represents a Christmas tree. You can adjust the parameters treeLevels, branchWidth, and treeHeight to customize the appearance of the tree. Additionally, you can add more decorations, such as ornaments or lights, by extending the code provided.

related categories

gistlibby LogSnag