【问题标题】:Define function as interpolation of x,y data将函数定义为 x,y 数据的插值
【发布时间】:2012-07-18 12:43:55
【问题描述】:

我在 data.txt 中有 2 列 x y 数据,如下所示:

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

现在我想定义一个函数 f(x),其中 x 是第一列,f(x) 是第二列,然后能够像这样打印这个函数的值:

f(2)

这应该给我 4 个。

我如何做到这一点?

【问题讨论】:

    标签: matlab function spatial-interpolation


    【解决方案1】:

    假设您想要一些返回值作为参考值之间的数字,您可以使用线性插值:

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

    更通用的函数版本可能是:

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

    然后您可以使用匿名函数创建特定实例:

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

    【讨论】:

    • 最上面的是我想要的那种东西,但是当我尝试它时它给了我一个错误:||的操作数和 && 运算符必须可转换为逻辑标量值。如果 l 1 test2>linearlut 中的错误(第 10 行) y = interp(xl,yl,x); test2(第 3 行)linearlut(1) 中的错误
    • 啊哈,通过将“interp”替换为“interp1”来修复它。更新答案,我会将其标记为已接受,谢谢
    • 对不起,我的回答太仓促了:)
    【解决方案2】:

    您可以使用textread() 导入文件,然后使用find 选择正确的行。

    在我的脑海中,未经测试:

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

    【讨论】:

      【解决方案3】:

      如果您只需要在数组中找到正确的值(无需插值),您可以使用:

      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);
      

      【讨论】:

        猜你喜欢
        • 2019-09-14
        • 1970-01-01
        • 2014-04-09
        • 2017-05-08
        • 2021-05-09
        • 2013-02-16
        • 2021-05-22
        • 2020-09-02
        • 2021-11-01
        相关资源
        最近更新 更多