MATLAB: How to Move the Patches fluidly without Leaving a Marking of the Patch at the previous Location

keypressfcn

if true
% code








end
clc
clear all
close all
if true
% code
end
global y
global y1
global h_rec
global h_rec1
if true
% code
end
h_fig=figure;
set(h_fig, 'KeyPressFcn', @kpfcn)
if true
% code
end
axis([-10 10 -10 10])
if true
% code
end
x=[2 2 4 4];
y=[2 4 2 4];
h_rec= patch(x,y,'k');
if true
% code
end
x1=[2 4 2 4];
y1=[2 2 4 4];
h_rec1= patch(x1,y1,'k');
if true
% code
end
refreshdata
function kpfcn(~, event)
global y
global y1
global h_rec
global h_rec1
if true
% code
end
switch event.Key
case 'uparrow'
x=[2 2 4 4];
x1=[2 4 2 4];
y=y+[1 1 1 1];
y1=y1+[1 1 1 1];
h_rec=patch(x,y,'k')
h_rec1=patch(x1,y1,'k')
case 'downarrow'
x=[2 2 4 4];
x1=[2 4 2 4];
y=y-[1 1 1 1];
y1=y1-[1 1 1 1];
h_rec=patch(x,y,'k')
h_rec1=patch(x1,y1,'k')
if true
% code
end
end
end

Best Answer

Do not patch() at the new location. Instead set the XData and YData properties of the existing patch object.
Alternatively, parent the patch im a hgtransform group, and each time you want to move it, change the transfom matrix of the group.