2

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], ... ]?

EBH
  • 10,083
  • 3
  • 29
  • 55
flor1an
  • 810
  • 12
  • 26

1 Answers1

3

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)

enter image description here

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
EBH
  • 10,083
  • 3
  • 29
  • 55