help-octave
[Top][All Lists]

## Re: Convert array to function

 From: Juan Pablo Carbajal Subject: Re: Convert array to function Date: Fri, 19 Dec 2014 15:58:20 +0100

```On Fri, Dec 19, 2014 at 12:36 PM, Marco <address@hidden> wrote:
> Hello,
>
> I have a problem and assume there's a simple solution. But I neither
> know octave nor maths that well. Maybe some of you guys can help
> out.
>
> 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 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?
>
> I looked into linear approximation, but that gives me a straight
> line through the points and no the required “steps”, thus
> introducing a very high error. I also found that polynom or spline
> approximation (using splinefit or polyfit) do not yield acceptable
> results. Any ideas?
>
> I am happy to provide further information or clarify things if
> unclear.
>
> Cheers,
> Marco
>
> _______________________________________________
> Help-octave mailing list
> https://lists.gnu.org/mailman/listinfo/help-octave

getting the polynomial and then evaluate using ppval.
This is done by the function
data2fun in the signal package
http://octave.sourceforge.net/signal/function/data2fun.html

But you can do it manually by

pp = interp1 (x,y,"linear","pp");

and then
func = @(x) ppval (pp,x);

```