Asked by Igor
on 20 May 2011

I don't see differences between... but - maybe @fun is more wide than inline-function

>> a

a =

1

>> x=1:10

x =

1 2 3 4 5 6 7 8 9 10

>> y=@(x) x.^a

y =

@(x)x.^a

>> y(x)

ans =

1 2 3 4 5 6 7 8 9 10

>> a=3

a =

3

>> y(x)

ans =

1 2 3 4 5 6 7 8 9 10

>> z=inline('x.^a','x')

z =

Inline function: z(x) = x.^a

>> z(x)

??? Error using ==> inlineeval at 15 Error in inline expression ==> x.^a Undefined function or variable 'a'.

*No products are associated with this question.*

Answer by Oleg Komarov
on 20 May 2011

Accepted answer

**Step 1** - define anonymous function in constant *a* and variable *x*:

a = 1; y = @(x) x.^a;

**Step 2** - change constant in the workspace, but the anonymous function remains unchanged since *a* was taken as a parameter in step 1

a = 3; y(x)

**Step 3** - in both cases the constant *a* is not defined at the moment the anonymous and inline fcns are created, thus the error in **both** cases

clear all y = @(x) x.^a; y(1)

z = inline('x.^a','x') z(x)

**Step 4** alternatives

y = @(x,a) x.^a; y(1,2)

z = inline('x.^a','x','a') z(1,2)

inline is an eval wrapper and is much slower than anonymous fcns.

Show 3 older comments

Titus Edelhofer
on 20 May 2011

Hi Igor,

for the "why": anonymous functions were "invented" as a replacement for the (somewhat ugly) inline.

Anonymous functions are much more robust then inline, same holds for using function handles in general instead of strings. Your example shows the difference: the function

@(x) x.^a

captures a at this very moment. What ever happens to a does not make a difference. This is in line with general behaviour: if you write

a = 42

x = 2*a;

a = 1;

you won't expect x to be 2. If a is indeed to be variable, use step 4.

Igor
on 20 May 2011

I asked another "why" -- concerning inline.

The error is due to "not enough input args" (like this), OR due to parser at calling ">> z(x)" hasn't recognized "a" as a fact variable.

Oleg Komarov
on 20 May 2011

I answered you in step 3

Related Content

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
## 1 Comment

## Varoujan (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/7860#comment_314922

Firstly, Matlab help files say that 'inline' function will be removed in future revisions. So, you better stick with the anonymous functions.

Second, your definition of inline function is wrong. When defined as inline, you have to provide the function all the inputs it needs. Change your code as follows: