How do I move objects around my MATLAB figure and how can I click and drag corners or points?

66 views (last 30 days)
I want to be able to click and drag Handle Graphics objects (lines, patches, and text) around on my plot. I would like to know if there is some way I can turn on the clicking and dragging feature.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 10 Apr 2023
Edited: MathWorks Support Team on 13 Apr 2023
The ability to click and drag corners or points and move objects around within a figure is not available in MATLAB. Such features of using the mouse to move data points are not possible.
As a workaround, try the user-contributed code, MOVEPLOT, which can be found on the MATLAB Central File Exchange:
You may also want to consider the user-contributed code, MOVEPLOT2:
Note that MathWorks does not guarantee or warrant the use or content of these submissions. Any questions, issues, or complaints should be directed to the contributing author.
Alternatively, you can use the following example as a guide to developing your own routine for moving points:
First make sure that the following two functions are on your MATLAB path:
rect.m
animator.m
Then you can use the following function code.
function rect(x)
if nargin <1
x = 'start';
end
switch x
case 'start'
figure;
axes('nextplot','replacechildren')
axis([0 5 0 5])
x = [0 1 1 0 0];
y = [0 0 1 1 0];
l1 = line(x,y);
set(l1,'Tag','Line1')
set(l1,'Buttondownfcn','animator(''start'')')
set(gca,'ButtonDownFcn','rect(''gcf_bdf'')')
case 'gcf_bdf'
l1 = findobj('tag','Line1');
% set(l1,'Selected','on')
A = get(gca,'CurrentPoint');
X = A(1,1);
Y = A(1,2);
XData = get(l1,'Xdata');
YData = get(l1,'Ydata');
[dX,Ix] = min(abs(XData-X));
[dY,Iy] = min(abs(YData-Y));
FinalX = X-XData(Ix);
FinalY = Y-YData(Iy);
XData = XData + FinalX;
YData = YData + FinalY;
set(l1,'Xdata',XData)
set(l1,'Ydata',YData)
end
function animator(action)
switch(action)
case 'start',
set(gcbf,'WindowButtonMotionFcn','animator move')
set(gcbf,'WindowButtonUpFcn','animator stop')
case 'move'
l1 = findobj('tag','Line1');
set(l1,'Selected','on')
XData = get(l1,'Xdata');
YData = get(l1,'Ydata');
currPt=get(gca,'CurrentPoint');
X = currPt(1,1);
Y = currPt(1,2);
FinalX = X-XData(3);
FinalY = Y-YData(3);
XData(2:3) = XData(2:3) + FinalX;
YData(3:4) = YData(3:4) + FinalY;
set(l1,'Xdata',XData)
set(l1,'Ydata',YData)
case 'stop'
set(gcbf,'WindowButtonMotionFcn','')
set(gcbf,'WindowButtonUpFcn','')
l1 = findobj('tag','Line1');
set(l1,'selected','off')
end

More Answers (0)

Categories

Find more on Graphics Object Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!