Home > 学习笔记 > Matlab中的匿名函数

Matlab中的匿名函数

转自 ncforest

匿名函数是MATLAB 7.0版提出的一种全新的函数描述形式,其基本格式为f=@(变量列表)函数内容,例如,f=@(x,y)sin(x.^2+y.^2)。其效率似乎比inline更高。
  更重要的,该函数允许直接使用MATLAB工作空间中的变量。 无需再将工作空间中的变量人微言轻附加参数在输入变量里表示出来,所以使得数学函数的定义更加方便。
例子:
我们知道以字符串形式存在的函数表达式可以通过inline函数转化成内联函数。现在的问题是,如何转化成更有效率的匿名函数?
     譬如a=’(x+y)^2′,我们可以通过f=inline(a),生成内联函数f(x,y)=(x+y)^2。
     现在问题是如何由a,由代码生成@(x,y) (x+y)^2?
a = ‘(x+y)^2′;
f = eval( sprintf(’@(x,y) %s’, a ));

f=eval(strcat(’@(x,y)’,a))

f=eval(['@(x,y)',a])

匿名函数的效率似乎比内联函数更高,做如下测试:
内联函数,大约5.4秒左右,匿名函数,大约3.4秒左右。

clear all;
clc;
syms x;
t1=clock;
r=0;
for y=1:100
a=x*log(x)*y+exp(x^3*y);
% f=inline(a);
f=eval(sprintf(’@(x) %s’,char(a)));
r=r+f(2);
end;
t2=etime(clock,t1);

Categories: 学习笔记 Tags:
  1. No comments yet.
  1. No trackbacks yet.
Note: Commenter is allowed to use '@User+blank' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC '(exclude ') will automatically send your comment to ABC. Using '@all ' to notify all previous commenters. Be sure that the value of User should exactly match with commenter's name (case sensitive).