Drawing a line between two dynamic points

5 visualizaciones (últimos 30 días)
Abdul Rauf Anwar
Abdul Rauf Anwar el 7 de Mzo. de 2025
Comentada: Jack el 8 de Mzo. de 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

Respuesta aceptada

Jack
Jack el 7 de Mzo. de 2025
Editada: Walter Roberson el 7 de Mzo. de 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 comentarios
Abdul Rauf Anwar
Abdul Rauf Anwar el 8 de Mzo. de 2025
Movida: Torsten el 8 de Mzo. de 2025
Thanks a lot!
It solved the issue
Jack
Jack el 8 de Mzo. de 2025

No problem!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Plot Customization en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by