Animate a rectangle, for loop used

37 views (last 30 days)
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
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
Anastasia Zistatsis
Anastasia Zistatsis on 17 Feb 2021
Thank you! I'm not sure how to use it. I'm trying to call it
r = rectangle('Position', [0.5 1.5 y1 y2]);
and then putting that in the plot(). My y values will be changing, how do I go about that?
Image Analyst
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

Sign in to comment.

More Answers (0)

Categories

Find more on Interactive Control and Callbacks 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!