Is there a good reason to choose between using inline functions vs anonymous functions in MATLAB? This exact question has been asked and answered here, but the answer is not helpful for rookie MATLAB users because the code snippets are incomplete so they do not run when pasted into the MATLAB command window. Can someone please provide an answer with code snippets that can be pasted into MATLAB?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Anonymous functions replaced inline functions (as mentioned in both the docs and in the link you posted)
The docs warn:
inline will be removed in a future release. Use Anonymous Functions instead.
回答2:
Here is how I would present Oleg's answer in my own style:
Case 1 - define anonymous function with parameter a
and argument xin
a = 1;
y = @(x) x.^a;
xin = 5;
y(xin)
% ans =
% 5
Case 2 - change parameter a
in the workspace to show that the anonymous function uses the original value of a
a = 3;
y(xin)
% ans =
% 5
Case 3 - both inline and anonymous functions cannot be used if they contain parameters that were undefined at the time of definition
clear all
y = @(x) x.^a;
xin = 5;
y(xin)
% ??? Undefined function or variable 'a'.
% Error in ==> @(x)x.^a
z = inline('x.^a','x');
z(xin)
% ??? Error using ==> inlineeval at 15
% Error in inline expression ==> x.^a
% ??? Error using ==> eval
% Undefined function or variable 'a'.
%
% Error in ==> inline.subsref at 27
% INLINE_OUT_ = inlineeval(INLINE_INPUTS_, INLINE_OBJ_.inputExpr, INLINE_OBJ_.expr);
Case 4 Comparing performance and passing a
as a variable.
clear all;
y = @(x,a) x.^a;
ain = 2;
xin = 5;
tic, y(xin, ain), toc
% ans =
% 25
% Elapsed time is 0.000089 seconds.
tic, z = inline('x.^a','x','a'), toc
z(xin, ain)
% z =
% Inline function:
% z(x,a) = x.^a
% Elapsed time is 0.007697 seconds.
% ans =
% 25
In terms of performance, anonymous >> inline.