draw line between points in the figure

points_id={'p1','p2','p3','p4'}
x=[100,120,130,140] %coordinates
y=[200,220,330,340] %coordinates
figure(1),scatter(x, y, 'b^');grid on;
text(x, y, points_id)
title('COORDINATE SYSTEM')
xlabel('Y')
ylabel('X')
% in this figure I wanna draw lines between points when user click on corresponding points.

 Accepted Answer

Get the points, for example by using ginput. Then find out which of the points is closest to the 2 points they clicked on. Then draw a line between them. Here's a demo:
clc;
clear all;
workspace
points_id={'p1','p2','p3','p4'}
x=[100,120,130,140] %coordinates
y=[200,220,330,340] %coordinates
figure(1),scatter(x, y, 'b^');
grid on;
text(x, y, points_id)
title('COORDINATE SYSTEM')
xlabel('Y')
ylabel('X')
uiwait(msgbox('Click on two points', 'modal'));
[xu, yu] = ginput(2);
% Find the closest point to the first point where they clicked.
distances1 = sqrt((x-xu(1)).^2 + (y - yu(1)).^2)
[~, index1] = min(distances1)
% Find the closest point to the second point where they clicked.
distances2 = sqrt((x-xu(2)).^2 + (y - yu(2)).^2)
[~, index2] = min(distances2)
line([x(index1), x(index2)], [y(index1), y(index2)])

6 Comments

When I want to continue drawing after 2 points, for example I wanna create polygon by clicking on 4 points or more what should I do?
Ask them in advance how many points they want to click on with inputdlg(). Then pass that number into ginput.
It is not known before, user decide it, it depends on the situation. What I want is users should be freely choose any points which they wanna draw polygon between them.
Then use the mousedown or buttondown callback function of the axes to draw a line from the closest last point (the one they just clicked on) to the prior point.
sermet
sermet on 29 Apr 2014
Edited: sermet on 29 Apr 2014
could you give example codes for what you meant please?
I don't have any sample/demo code for that. Either you or I would have to write it. I vote for you.

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!