【发布时间】: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
我在 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
假设您想要一些返回值作为参考值之间的数字,您可以使用线性插值:
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);
【讨论】:
您可以使用textread() 导入文件,然后使用find 选择正确的行。
在我的脑海中,未经测试:
function y = findinfile(x)
m = textread(data.txt)
ind = find(m(:,1)==x)
y = m(ind,2)
end
【讨论】:
如果您只需要在数组中找到正确的值(无需插值),您可以使用:
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);
【讨论】: