[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
## RE: Convert array to function

**From**: |
Allen.Windhorn |

**Subject**: |
RE: Convert array to function |

**Date**: |
Fri, 19 Dec 2014 14:56:38 +0000 |

Marco,
>* -----Original Message-----*
>* From: address@hidden*
>* *
>* I have a curve that is described as a vector v with n-elements,*
>* each containing a pair:*
>* *
>* v=[0,0; 2,2; 4,2; 6,6; 10,6]*
>* *
>* ASCII-art visualised:*
>* *
>* ^*
>* |*
>* 10|*
>* |*
>* 8|*
>* |*
>* 6| xxxxxxxxx*
>* | x*
>* 4| x*
>* | x*
>* 2| xxxxx*
>* | x*
>* +---------------------->*
>* 0 2 4 6 8 10*
>* *
>* I am only interested in the x-range [0:10] meaning the values below*
>* 0 and above 10 can be ignored.*
>* *
>* Vector v is given and I have to define a function that evaluates to*
>* the points described by the vector. The points are always connected*
>* by straight lines. So the function should (with the example values*
>* for v as stated above) at point 1 evaluate to 1, at point 2*
>* evaluate to 2, at point 8 evaluate to 6, etc.*
>* *
>* The pairs are not necessarily equally spaced and the number of*
>* elements in v is not constant. (This will be automated and the v is*
>* the input I receive.)*
>* *
>* The question: Is there an octave function which I can feed the*
>* vector with pairs (v) and obtain a function which I can evaluate at*
>* any point within the range?*
Linear interpolation using interp1 works.
octave:3> v=[0,0; 2,2; 4,2; 6,6; 10,6]
v =
0 0
2 2
4 2
6 6
10 6
% Split the vector into x and y parts:
octave:4> x = v(:,1)
xx =
0
2
4
6
10
octave:5> y = v(:,2)
yy =
0
2
2
6
6
% Make a function from the table:
octave:11> f = @(x) interp1(xx, yy, x);
% See if it works:
octave:11> x = 0:0.5:10
octave:12> y = f(x);
octave:13> plot(x,y)
% Success!
Regards,
Allen