Connect two set of points with a line based in the index

泪湿孤枕 提交于 2019-12-11 03:35:38

问题


What I'm trying to do is connecting two sets of points (x,y based) with a line. The line should be drawn based on the index of the two sets. Meaning set1(x,y) should be connected to set2(x,y) where x and y are the same indices in both sets.

What I have so far is the following:

set1 = [1,2; 3,4; 5,6];
set2 = [10,20; 30,40; 50,60];
plot(set1(:,1),set1(:,2),'b+',set2(:,1),set2(:,2),'g+')

Displaying me the items of set1 in blue points and the set2 in green points. Meaning I want to plot a line between [1,2] and [10,20]

Is there any build-in function for this, or do I need to create a third set representing the lines e.g. [ [1,2; 10,20], [3,4; 30,40], ... ]?


回答1:


You don't need to build a function, just to use plot correctly. If you input a matrix of x values and a matrix of y values, then plot interprets it as multiple series of data, where each column is a data series.

So if you reorganize you sets to:

x = [set1(:,1) set2(:,1)].'
y = [set1(:,2) set2(:,2)].'

then you can just type:

plot(x,y)

The code with our data:

set1 = [1,2; 3,4; 5,6];
set2 = [10,20; 30,40; 50,60];
plot(set1(:,1),set1(:,2),'b+',set2(:,1),set2(:,2),'g+')
hold on
x = [set1(:,1) set2(:,1)].';
y = [set1(:,2) set2(:,2)].';
plot(x,y,'r')
hold off


来源:https://stackoverflow.com/questions/45442286/connect-two-set-of-points-with-a-line-based-in-the-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!