Animate a rectangle, for loop used
15 views (last 30 days)
Show older comments
Anastasia Zistatsis
on 16 Feb 2021
Commented: Image Analyst
on 17 Feb 2021
Hello! The code below takes a large matrix (x) and shows 'o' moving up and down on a plot. I would like to change the 'o' into a rectangle moving in the same way, hanging by a string. How would I do this?
for i = 1:125
plot(x(i),'o')
axis([0 5 -5 5])
y(i) = getframe
end
movie(y,25,25)
Accepted Answer
Image Analyst
on 17 Feb 2021
Use the rectangle() function. Get it's handle so you can delete the old one when you want to place a new one.
2 Comments
Image Analyst
on 17 Feb 2021
Anastasia, see this little animation demo.
% Initialization steps.
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
clear; % Erase all existing variables. Or clearvars if you want.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 13;
% Define oscillation parameters.
period = 10;
t = linspace(0, 5 * pi, 100);
y = 30 * sin(2 * pi * t / period);
% Define graphics parameters:
rectangleHeight = 10;
rectangleWidth = 10;
rectangleX1 = 10;
lineX = 15;
% Set up axes.
grid on;
ylim([-50, 50]);
xlim([0, 30]);
xlabel('X', 'FontSize', 15);
ylabel('Y', 'FontSize', 15);
% Start the movement:
for k = 1 : length(y)
caption = sprintf('Iteration %d, y(%d) = %f', k, k, y(k));
fprintf('%s\n', caption);
% Place a rectangle at the current y location.
r = rectangle('Position', [rectangleX1, y(k), rectangleWidth, rectangleHeight], 'FaceColor', 'r');
title(caption, 'FontSize', 15);
% Drawline from to to top of rectangle.
hLine = line([lineX, lineX], [50, y(k)+rectangleHeight], 'LineWidth', 5, 'Color', 'b');
drawnow;
% Wait long enough to see it at this location.
pause(0.1)
% Delete the rectangle to prepare for the next one.
if k < length(y) % Don't delete the very last one.
delete(r);
delete(hLine);
end
end
More Answers (0)
See Also
Categories
Find more on Animation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!