Asked by sim_892
on 22 Nov 2019 at 2:51

Hi, I am following the recommended way to create variables with sequential names: https://de.mathworks.com/help/matlab/matlab_prog/string-evaluation.html

However, each one of my variables in the cell array is a function with function handle, I am trying this:

numArrays = 10;

A = cell(numArrays,1);

for n = 1:numArrays

A {n} = @ {beta} 0.5 * (beta (n) + beta (n + 1));

end

For every cell of my cell array I would like to get: @(beta)0.5*(beta(1)+beta(2)), @(beta)0.5*(beta(2)+beta(3)), @(beta)0.5*(beta(3)+beta(4)).....

But instead I get this: @(beta)0.5*(beta(n)+beta(n+1)), @(beta)0.5*(beta(n)+beta(n+1)), @(beta)0.5*(beta(n)+beta(n+1)) ....

Thank you for your help.

Answer by Steven Lord
on 22 Nov 2019 at 5:08

The anonymous function "remembers" the value n had when the anonymous function was created, so it will do what you want when it is called. You can check what the anonymous function "remembers" using the functions function. [As its documentation states, you should only use this for diagnostic and debugging purposes.]

To answer what I expect you will ask next:

- No, there is no way to have the anonymous function use the "remembered" value as part of its display.
- No, there is no way to change the "remembered" value of n without recreating the anonymous function.

But rather than create a bunch of anonymous functions that are all very similar, why not just create one that's more flexible?

A = @(beta, n) 0.5*(beta(n) + beta(n+1));

Or if you want a function that will process all of beta at once, look at movsum and/or movmean.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 1 Comment

## Stephen Cobeldick (view profile)

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/492502-variables-with-sequential-names-with-function-handle#comment_770109

Sign in to comment.