Draw lines between points

234 ビュー (過去 30 日間)
Emi
Emi 2013 年 12 月 4 日
編集済み: Walter Roberson 2016 年 5 月 2 日
I have a text file ("coordinates.txt") that contains x and y coordinates of points.
File looks like this:
11 44 2 9
11 44 5 8
2 1 6 11
2 1 10 3
I need to draw lines between (11, 44) to (2, 9), (11, 44) to (5, 8), (2, 1) to (6, 11), and (2, 1) to (10, 3).
I can do this by manually like:
x = [11 11 2 1; 2, 5, 6, 10];
y = [44 44 1 1; 9 8 11 3];
plot (x, y).
But the actual file is quite long and I need to "automate" this process.
I tried:
load coordinates.txt;
edit coordinates.txt;
x1= [coordinates(:, 1); coordinates(:, 3)];
y1 = [coordinates(:, 2); coordinates(:, 4)];
plot (x1, y1).
It gives me lines drawn from (11, 44) to (2, 9), (2, 9) to (5, 8), (5, 8) to (6, 11), (6, 11) to (10, 3).
Could anyone help?

採用された回答

dpb
dpb 2013 年 12 月 4 日
Simply read in the array as it is in the file, then if
m =
11 44 2 9
11 44 5 8
2 1 6 11
2 1 10 3
for instance,
>> x=[m(:,1) m(:,3)];
>> y=[m(:,2) m(:,4)];
>> plot(x',y')
Or, you can do w/o the temporaries x, y of course if there's no other need to separate.
NB: I'm presuming the actual example x
x = [11 11 2 1; 2, 5, 6, 10];
contains a typo given the content of the file in that the '1' on the first line should also be a '2'...
  1 件のコメント
Emi
Emi 2013 年 12 月 4 日
It worked!! Thank you! And yes, it was a typo.

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

その他の回答 (2 件)

Kelly Kearney
Kelly Kearney 2013 年 12 月 4 日
Matlab considers each column passed to plot to represent a separate line segment. So just transpose your data:
plot(x1', y1')

Bandar
Bandar 2014 年 6 月 2 日
編集済み: Bandar 2014 年 6 月 2 日
In this case you better build your own function to draw a line given two points.
function [] = drawLine(p1, p2)
theta = atan2( p2(2) - p1(2), p2(1) - p1(1));
r = sqrt( (p2(1) - p1(1))^2 + (p2(2) - p1(2))^2);
line = 0:0.01: r;
x = p1(1) + line*cos(theta);
y = p1(2) + line*sin(theta);
plot(x, y)
in the main function do the following
>> drawLine([0 0], [-5 5])
>> hold on
>> drawLine([0 0], [5 5])
For many points just put `drawLine` in a loop. Hope this helps

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by