Passing indexed variable value to be stored in cell array rather than reference
Show older comments
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)
Daniel Shub
on 20 Mar 2012
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".
Am
on 20 Mar 2012
1 Comment
Daniel Shub
on 25 Mar 2012
Without more details, it is hard to debug. I would pass it on the TMW and see what they come up with.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!