function handles
    5 views (last 30 days)
  
       Show older comments
    
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
0 Comments
Answers (1)
  Pratyush Swain
      
 on 21 Mar 2025
        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.
0 Comments
See Also
Categories
				Find more on Polygons in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
