Animate a rectangle, for loop used

15 visualizzazioni (ultimi 30 giorni)
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)

Risposta accettata

Image Analyst
Image Analyst il 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 Commenti
Anastasia Zistatsis
Anastasia Zistatsis il 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 il 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Animation in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by