Define function as interpolation of x,y data

2019-05-28 13:13发布

问题:

I have 2 columns of x y data in data.txt like this:

0  0
1  1
2  4
3  9
4  16
5  25

Now I want to define a function f(x) where x is the first column and f(x) is the second column, and then be able to print values of this function like so:

f(2)

Which should give me 4.

How do I achieve this?

回答1:

Assuming that you want some return value for numbers between the ones you have as reference, you can use linear interpolation:

    function y= linearLut(x)
         xl = [0 1 2 3 4 5];
         yl = [0 1 4 9 16 25];
         y = interp1(xl,yl,x);
    end

A more generic version of the function might be:

    function y= linearLut(xl,yl,x)
         y = interp1(xl,yl,x);
    end

And then you can create specific instances by using anonymous functions:

    f = @(x)(linearLut([0 1 2 3 4],[0 1 4 9 16],x));
    f(4);


回答2:

You can import the file using textread(), then use find in order to select the right row.

Out of my head and untested:

function y = findinfile(x)
    m = textread(data.txt)
    ind = find(m(:,1)==x)
    y = m(ind,2)
end


回答3:

If you only need to find the correct value in the array (without interpolation) you can use:

function out=ff(b)
  a = [0 1 2 3 4 5 ; 3 4 5 6 7 8]';
  [c,d]=find(a(:,1)==b);
  out = a(c,2);