function handles

1 次查看(过去 30 天)
Mallory
Mallory 2012-1-28
hei guys,i have a problem with function usage and i kinda get confused with it .my function works when i change the position of the polygon (created with impoly), and it will automatically call the second function that make a new patch that fill the polygon new position. the problem is when i change the position of the polygon, the function keeps on making new patches. is there a way to fill colors while we change the polygon's position?
here is the script that i've wrote
function polygon
axis([0 100 0 100])
h = impoly(gca,[10 10 ; 20 10; 20 20 ; 10 20]);
api = iptgetapi(h);
current_body_coordinates = api.getPosition();
patches(current_body_coordinates)
api.addNewPositionCallback(@patches);
function patches(p)
patches=patch(p(:,1),p(:,2),'r');
thanks in advance :D

回答(1 个)

Pratyush Swain
Pratyush Swain 2025-3-21
Hi Mallory,
The problem arises because each time the polygon's position changes, a new patch is created without removing the previous one.
We can update the position of the patch instead of creating a new patch each time:
function polygon
axis([0 100 0 100])
% Create the polygon
h = impoly(gca,[10 10 ; 20 10; 20 20 ; 10 20]);
api = iptgetapi(h);
current_body_coordinates = api.getPosition();
% Create a patch using the initial position
poly_patch = patch(current_body_coordinates(:,1), current_body_coordinates(:,2), 'r');
% Callback to update the patch
api.addNewPositionCallback(@update_patch);
% Function to update patch
function update_patch(p)
set(poly_patch, 'XData', p(:,1), 'YData', p(:,2));
end
end
For more information on 'patch' function, you can refer to - https://www.mathworks.com/help/matlab/ref/patch.html
Hope this helps.

类别

Help CenterFile Exchange 中查找有关 Polygons 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by