Passing indexed variable value to be stored in cell array rather than reference

Hello,
I am trying this:
c = cell(1,n);
for i = 1:n
c(1,i) = {@(x,optimValues,state)outfun(x,optimValues,state,i)};
end
With the goal of creating a 1xn cell array that stores the outfun reference with the "extra" parameter i.
It is mostly correct, but it gives me a 1xn cell with all of its elements identical to this statement: {..@(x,optimValues,state)outfun(x,optimValues,state,i)..}
What I want is to store the actual value of i in each loop, rather than i itself. i.e. I need to end with with a 1xn cell array that looks like this
{@(x,optimValues,state)outfun(x,optimValues,state,1)... @(x,optimValues,state)outfun(x,optimValues,state,2)... ... @(x,optimValues,state)outfun(x,optimValues,state,n)}
Any way how to get around to accomplishing this?

Answers (2)

I think you have what you want. It just doesn't display the way you expect it to. Consider this simplified example
n = 3;
c = cell(1,n);
for i = 1:n
c(1,i) = {@()i};
end
c
gives c = @()i @()i @()i. The key is that each i has a different value within the context of the function handle. You can see this by doing
x = c{1};
y = c{2};
z = c{3};
for i = 1:n
[x(), y(), z()]
end
and realizing that the result is always [1 2 3], even if i is changing in the workspace.
Basically the value of the variables in function handles get fixed at the time of creation of the function handle. Despite looking like a reference, they are in fact "indexed".
Thanks Daniel for the response. Much appreciated
It seems like then something else is amiss...
Basically if I create the cell array "manually" as follows for example:
c = {@(x,optimValues,state)outfun(x,optimValues,state,1) @(x,optimValues,state)outfun(x,optimValues,state,2) ... @(x,optimValues,state)outfun(x,optimValues,state,n) }
and then pass it into:
options = optimset(.....'PlotFcn', c)
i.e. as a variable input into a built-in matlab function (the function accepts a cell array as input, FYI it is the optimset function) then everything works just as expected. But because I need the cell array to be generated for different values of n, putting in the for-loop code:
c = cell(1,n);
for i = 1:n
c(1,i) = {@(x,optimValues,state)outfun(x,optimValues,state,i)};
end
options = optimset(.....'PlotFcn', c)
does NOT work.
the only difference I can see is when I look at the c cell array in the workspace, the for-loop generated c has n elements, all referencing the letter i, rather than holding the values of i.

1 Comment

Without more details, it is hard to debug. I would pass it on the TMW and see what they come up with.

Sign in to comment.

Asked:

Am
on 20 Mar 2012

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!