Matlab:将函数作为函数的参数传递

时间:2013-05-26 09:28:55

标签: matlab function

我想要构建的功能是:

function y = myfunction(data, @f1, @f2, @f3, @f4)
%Fit data using f1,f2,f3,f4 such that data ~ af1+bf2+cf3+df4
end

其中data是一个数组。用户将定义f1f2f3f4,选择sin(x)cos(x)ln(x)中的四个函数, 1/xtan(x)tanh(x)1/ln(x) ......等等。

我的目标是使data函数符合af1+bf2+cf3+df4,其中a,b,c,d是系数。问题是我不知道如何将函数作为输入传递并在myfunction内使用它们。我怎样才能做到这一点?一个小例子就足够了。

3 个答案:

答案 0 :(得分:3)

你只需要将它们作为标准参数,就像使用任何其他参数一样

function y = myfunction(data, f1, f2, f3, f4)
    % ...
end

这些参数是function_handle类型的变量(只要您实际传递函数句柄)。要使用一组函数句柄调用此函数,您可以执行

f1 = @sin; f2 = @cos; f3 = @ln; f4 = @(x)1/x;
myfunction(data, f1, f2, f3, f4);

要创建另一个将所有四个结果相加的匿名函数,您可以

fTotal = @(x)f1(x) + f2(x) + f3(x) + f4(x);

有关详细信息,请参阅Anonymous Functions

答案 1 :(得分:3)

像这样:

function y = myfunction(data, f1, f2, f3, f4)
  fprintf('f1(2) = %d\n', f1(2) );
  fprintf('f2(10) = %d\n', f2(10) );
  fprintf('f3(1) = %d\n', f3(1) );
  fprintf('f4(0.1) = %d\n', f4(0.1) );
end

myfunction(@sin, @cos, @ln, @tan);
myfunction(@cos, @sin, @tanh, @ln);

我刚刚将myfunction打印出一些随机值作为演示。

请注意以下事项:

  • 要将函数传递给myfunction,我使用了函数句柄:@sin
  • myfunction 的参数不需要@符号:它们只是普通变量。
  • 一旦你有一个存储函数句柄的变量,你可以“调用”变量,就像它是一个函数一样:f1(x)

答案 2 :(得分:1)

你传递它们就像你对任何其他物体一样。仅在定义匿名函数时才需要'@',而不是在将它们作为参数传递时。

function y = myfun1(data, f1);
   y = f1(data);
end

f = @(x)(1./x);
d = 1:4;

disp( myfun1(d, f) );

会给你

1.0000    0.5000    0.3333    0.2500

并将其扩展到更多功能是很简单的。