Drawing a line between two dynamic points

6 次查看(过去 30 天)
Hi
I am making this app, in which i have to draw a line between two points (coordinates). The value of these points keep on changing so with every click a new line needs to be drawn (old one gets removed). You can think of this as a very simple see saw, whose two ends move up and down. I believe that i cannot draw a line on ui.figure, however a line can be drawn on UIAxes, but I am unble to manipulate/translate the two points (coordinates) on UIAxes. Any help in this regard will be greatly appreciated.
Thanks
Rauf

采纳的回答

Jack
Jack 2025-3-7
编辑:Walter Roberson 2025-3-7
Hey Rauf,
You're on the right track—you can't draw a line directly on a uifigure, but you can draw it on UIAxes. The key here is to update the line every time your points change instead of plotting a new one on top of the old one.
Here’s a simple way to do it:
  1. Use plot to create the initial line in your UIAxes.
  2. Update the XData and YData of the line object instead of re-plotting.
Example Code (App Designer)
function startupFcn(app)
% Initial points
app.P1 = [0, 0];
app.P2 = [1, 1];
% Create the line and store its handle
hold(app.UIAxes, 'on');
app.LineHandle = plot(app.UIAxes, [app.P1(1), app.P2(1)], [app.P1(2), app.P2(2)], 'r-', 'LineWidth', 2);
end
function UpdateLine(app)
% New dynamic points (replace these with your own logic)
app.P1 = app.P1 + rand(1,2) * 0.1; % Example update
app.P2 = app.P2 + rand(1,2) * 0.1;
% Update the line without re-plotting
app.LineHandle.XData = [app.P1(1), app.P2(1)];
app.LineHandle.YData = [app.P1(2), app.P2(2)];
end
% Call UpdateLine() whenever you need to refresh the line
How This Works
  • startupFcn initializes the plot once and stores the line handle.
  • UpdateLine updates the XData and YData properties without redrawing the entire figure.
  • No flickering, no unnecessary new lines stacking up!
If you’re triggering updates on button clicks or real-time changes, just call UpdateLine(app). Should work smoothly! 🚀
If this helps, follow me so you can message me anytime with future MATLAB or Simulink questions! 🚀
  4 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

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

产品


版本

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by