Drawing a line between two dynamic points

5 ビュー (過去 30 日間)
Abdul Rauf Anwar
Abdul Rauf Anwar 2025 年 3 月 7 日
コメント済み: Jack 2025 年 3 月 8 日
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 件のコメント
Abdul Rauf Anwar
Abdul Rauf Anwar 2025 年 3 月 8 日
移動済み: Torsten 2025 年 3 月 8 日
Thanks a lot!
It solved the issue
Jack
Jack 2025 年 3 月 8 日

No problem!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePlot Customization についてさらに検索

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by