Matlab inline VS anonymous functions

∥☆過路亽.° 提交于 2020-01-04 04:29:09

问题


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.



来源:https://stackoverflow.com/questions/18253157/matlab-inline-vs-anonymous-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!