2

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.

duplode
  • 33,731
  • 7
  • 79
  • 150
user1011182
  • 43
  • 1
  • 7
  • I think you mean to create a function `[xi, yi] = makeline(x1,y1,x2,y2, N)` right? Or do you really want to create a function that returns a new function? – Gunther Struyf Nov 03 '12 at 16:59

2 Answers2

2

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.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • I think you mixed up x and y in the linspace call, it makes more sense to me if you have `linspace(x(1),x(2),npoints)` and vice versa for `y` – Gunther Struyf Nov 03 '12 at 17:02
1

If you want a function that returns another function to create the line, take a look at anonymous functions:

function fun = makelinefun(x1,y1,x2,y2)
    fun  = @(N) [linspace(x1,x2,N) ; linspace(y1,y2,N)];
end

which you use as:

f = makelinefun(0,0,6,9);
xy = f(4)

  xy =
      0     2     4     6
      0     3     6     9

OR with multiple output arguments:

function fun  = makelinefun(x1,y1,x2,y2)
    fun  = @(N) deal(linspace(x1,x2,N), linspace(y1,y2,N));
end

which you use as:

f = makelinefun(0,0,6,9);
[x,y] = f(4)

  x =
      0     2     4     6
  y =
      0     3     6     9
Gunther Struyf
  • 11,158
  • 2
  • 34
  • 58