Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab inline VS anonymous functions

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?

like image 312
Chad Avatar asked Aug 13 '26 16:08

Chad


2 Answers

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.

like image 156
Dan Avatar answered Aug 16 '26 19:08

Dan


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.

like image 29
5 revsChad Avatar answered Aug 16 '26 21:08

5 revsChad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!