create fireworks animation in matlab

Here's an example code to create a simple fireworks animation in Matlab:

main.m
% Set up the figure
figure;
axis([0, 1, 0, 1]); % set the limits (x_min, x_max, y_min, y_max)

hold on; % keep all the plots

% Center of the explosion
cx = 0.5;
cy = 0.5;

% Create the explosion
n_particles = 50; % number of particles
colors = winter(n_particles); % define the colors

for i = 1:n_particles
    r = rand*0.05; % radius
    theta = rand*2*pi; % angle
    x = cx + r*cos(theta); % position
    y = cy + r*sin(theta);
    h(i) = plot(x, y, '.', 'Color', colors(i,:), 'MarkerSize', 20); % create the particles
    v_x(i) = randn*0.05; % x-velocity
    v_y(i) = randn*0.05; % y-velocity
end

% Animate the explosion
for t = 1:100 % number of frames
    for i = 1:n_particles
        set(h(i), 'XData', get(h(i), 'XData') + v_x(i), ...
                  'YData', get(h(i), 'YData') + v_y(i)); % update position
        v_y(i) = v_y(i) - 0.01; % apply gravity
    end
    drawnow; % refresh the figure
    pause(0.05); % pause to set the speed of the animation
end

hold off; % release the plots
1007 chars
37 lines

The code creates a figure with a square of size (1 x 1), where a simple explosion is created in the center of it. It first defines the number of particles and their position, velocity, and colors, then animates the particles by updating their positions at every frame and applying gravity to them. Finally, the animation is refreshed and paused to set the speed of the explosion.

related categories

gistlibby LogSnag