5

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Eddy
  • 6,661
  • 21
  • 58
  • 71

3 Answers3

5

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);
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
  • The top one is the sort of thing I want, however it gives me an error when I try it: Operands to the || and && operators must be convertible to logical scalar values. Error in interp (line 44) if l < 1 || r < 1 || cutoff <= 0 || cutoff > 1 Error in test2>linearlut (line 10) y = interp(xl,yl,x); Error in test2 (line 3) linearlut(1) – Eddy Jul 19 '12 at 10:55
  • Aha, fixed it by replacing 'interp' with 'interp1'. Update the answer and I will mark it accepted, thanks – Eddy Jul 19 '12 at 11:06
  • Sorry for the mistake, I was too hasty with my answer :) – Andrey Rubshtein Jul 19 '12 at 11:09
0

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
Herr von Wurst
  • 2,571
  • 5
  • 32
  • 53
0

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);
Tal Darom
  • 1,379
  • 1
  • 8
  • 26