MATLAB: How to make an animation of changing dimension rectangle in Matlab

animationfigurehgtransformmakehgtformMATLABrectangle

I am trying to do an animation, with a rectangle, which should change dimension every time it touch the wall (taller and thinner). I did something like that, and it is not so bad, but area should be always the same and now it is not. Other bad thing is that it is not touching right wall. And it should be always on this same height but it's not. Can You please help me with these problems?
My code:
clear all;
clc;
x=[0 0 100 100 0];
y=[0 100 100 0 0];
plot(x,y,'black');
axis([-10 110 -10 110]);
hold on;
g = hgtransform;
x=[50 50 100 100 50];
y=[37.5 62.5 62.5 37.5 37.5];
patch('XData',x,'YData',y,'FaceColor','white','Parent',g)
pt1 = [-50 0 0];
pt2 =[1 1 1]
for i=1:1:1000
for t=linspace(0,1,250)
b = makehgtform('scale',pt2,'translate',t*(pt1));
set(g,'Matrix',b)
drawnow
end
pt2=pt2+[-0.125 0.125 0];
for t=linspace(1,0,250)
b = makehgtform('scale',pt2,'translate',t*(pt1));
set(g,'Matrix',b)
drawnow
end
pt2=pt2+[-0.125 0.125 0];
end

Best Answer

clc;
x=[-50 -50 50 50 -50];
y=[-50 50 50 -50 -50];
plot(x,y,'black');
axis([-60 60 -60 60]);
hold on;
x=[-25 -25 25 25 -25];
y=[-12.5 12.5 12.5 -12.5 -12.5];
p = patch('XData',x,'YData',y,'FaceColor','white');
pt2 = [1 1 1];
time_instants = 250;
for i=1:1:1000
% right to left
right_max = 50 - max(x);
left_max = -50 - min(x);
for t=linspace(right_max, left_max, time_instants)
p.Vertices(:,1) = x' + t;
drawnow
end
pt2=pt2+[-0.125 0.125 0];
x = x*pt2(1);
y = y*pt2(2);
p.Vertices(:,2) = y;
% left to right
right_max = 50 - max(x);
left_max = -50 - min(x);
for t=linspace(left_max, right_max, time_instants)
p.Vertices(:,1) = x' + t;
drawnow
end
pt2=pt2+[-0.125 0.125 0];
x = x*pt2(1);
y = y*pt2(2);
p.Vertices(:,2) = y;
end