Matlab, Straight Line between 2 points with n points between

user1011182 picture user1011182 · Nov 3, 2012 · Viewed 7.4k times · Source

I want to make a function that will take 2 data points: (x1, y1) and (x2, y2).

Then I want to return a function f, which is the straight line between the points with N points in between.

If I take in the x and y coordinates of the 2 data points then can I do:

step_size = (x2 - x1) / N;
range = x1:step_size:x2;

and then:

f = ((y2 - y1)/(x2 - x1)) * range + ((y1/x1) * ((x2 - x1)/(y2 - y1)));

Will this suffice?

Furthermore, I've been searching online and couldn't find any function already out there that does this. But if there is then please advise.

Answer

High Performance Mark picture High Performance Mark · Nov 3, 2012

You're looking for linspace. For example, define

x1 = 0; y1 = 0; x2 = 4; y2 = 4; npoints=6;

then

[linspace(x(1),y(1),npoints);linspace(x(2),y(2),npoints)]

evaluates to:

ans =

         0    0.8000    1.6000    2.4000    3.2000    4.0000
         0    0.8000    1.6000    2.4000    3.2000    4.0000

That's probably not exactly what you want, but I guess you can figure out the rest.

Furthermore, if you type edit linspace.m you can see how the function is implemented should you want to create your own version, one that works on 2-element vectors perhaps.