plot a christmas tree in matlab

Here is a code snippet to plot a Christmas tree in matlab:

main.m
% Set up the figure
figure();
hold on;

% Define the base of the tree
x = linspace(-1,1,1000);
y = zeros(size(x));

% Plot the green part of the tree
for i=1:7
    xp = linspace(-1+(i-1)*0.2,1-(i-1)*0.2,1000);
    yp = -0.25*i+0.75*sqrt(1-(abs(xp)-abs((i-1)*0.2)).^2);
    plot(xp,yp,'Color',[0 0.5 0],'LineWidth',3)
end

% Plot the trunk of the tree
xp = linspace(-0.2,0.2,1000);
yp = -2+sin(10*xp);
plot(xp,yp,'Color',[0.5 0.25 0],'LineWidth',6)

% Add decorations to the tree
star = plot(0,2,'*','Color','y','MarkerSize',25,'LineWidth',2);
lights = scatter(2*(rand(50,1)-0.5),2*(rand(50,1)-0.5),30,rand(50,3),'filled');

% Add a title and axis labels
title('Merry Christmas from Matlab!');
xlabel('x');
ylabel('y');

% Add a legend
legend([star,lights],{'Star','Lights'},'Location','northwest');

% Set the axis limits
xlim([-1.5 1.5]);
ylim([-2.5 2.5]);
858 chars
36 lines

This code uses basic trigonometry to plot the green part of the tree and a sin function to plot the trunk. The decorations are added using the plot and scatter functions, and a legend is added using the legend function. The resulting figure should look like a Christmas tree with a star and lights.

gistlibby LogSnag