Animate a rectangle, for loop used

조회 수: 20 (최근 30일)
Anastasia Zistatsis
Anastasia Zistatsis 2021년 2월 16일
댓글: Image Analyst 2021년 2월 17일
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
Anastasia Zistatsis 2021년 2월 17일
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