Drawing a line between two dynamic points

6 vues (au cours des 30 derniers jours)
Abdul Rauf Anwar
Abdul Rauf Anwar le 7 Mar 2025
Commenté : Jack le 8 Mar 2025
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

Réponse acceptée

Jack
Jack le 7 Mar 2025
Modifié(e) : Walter Roberson le 7 Mar 2025
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 commentaires
Abdul Rauf Anwar
Abdul Rauf Anwar le 8 Mar 2025
Déplacé(e) : Torsten le 8 Mar 2025
Thanks a lot!
It solved the issue
Jack
Jack le 8 Mar 2025

No problem!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Plot Customization dans Help Center et File Exchange

Produits


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by