MATLAB: How to use a for loop counter in an anonymous function

anonymousarrayfor loopfunctionMATLABvariable

I currently have a loop that creates anonymous functions using values from arrays, and I need the 'p' value to be used within the loop to create the anonymous function so that values from other arrays are assigned to it.
for p = 1:5
dydxLeft(:, p) = dydx(pLeft(:, p));
dydxRight(:, p) = dydx(pRight(:, p));
dfLeft(:, p) = dydx(dydxLeft(:, p));
dfRight(:, p) = dydx(dydxRight(:, p));
sub_left_dydx{p} = @(t) dydxLeft(1, p).*t.^3 + dydxLeft(2, p).*t.^2 + dydxLeft(3, p).*t + dydxLeft(4, p);
sub_right_dydx{p} = @(t) dydxRight(1, p).*t.^3 + dydxRight(2, p).*t.^2 + dydxRight(3, p).*t + dydxRight(4, p);
sub_left_df{p} = @(t) dfLeft(1, p).*t.^2 + dfLeft(2, p).*t + dfLeft(3, p);
sub_right_df{p} = @(t) dfRight(1, p).*t.^2 + dfRight(2, p).*t + dfRight(3, p);
end
The current output for the anonymous function sub_left_dydx{1} is:
@(t) dydxLeft(1,p).*t.^3 + dydxLeft(2,p).*t.^2 + dydxLeft(3,p).*t + dydxLeft(4,p)
Whereas what I am looking for is:
@(t) dydxLeft(1,1).*t.^3 + dydxLeft(2,1).*t.^2 + dydxLeft(3,1).*t + dydxLeft(4,1)
How can I achieve this?

Best Answer

I don't think you have a real problem, other than in appearance. At the creation of the function handle, a snapshot of the variable p is taken and becomes part of the function handle itself. So the current value of p, at the time of the function handle creation, is what is used in that particular function handle. E.g.,
>> p = 1
p =
1
>> f{1} = @(t) t.^p
f =
@(t)t.^p
>> p = 2
p =
2
>> f{2} = @(t) t.^p
f =
@(t)t.^p @(t)t.^p
>> f{1}
ans =
@(t)t.^p
>> f{2}
ans =
@(t)t.^p
>> f{1}(3)
ans =
3
>> f{2}(3)
ans =
9
I know it looks funny, having the function handles appearing to be exactly the same, but in fact they are not since they are using different snapshots of the variable p at the time they were created. As long as this appearance doesn't bother you, I think the code still does what you want.