Animate a rectangle, for loop used

24 次查看(过去 30 天)
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)

采纳的回答

Image Analyst
Image Analyst 2021-2-17
Use the rectangle() function. Get it's handle so you can delete the old one when you want to place a new one.
  2 个评论
Anastasia Zistatsis
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 2021-2-17
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by