MATLAB: How to pass a workspace variable as a parameter to STR2FUNC in MATLAB 7.11 (R2011a)

inputMATLABparameterstr2funcundefinedvariable

I am using STR2FUNC to construct a function handle from a string and I would like to pass a workspace variable as a parameter to the function. In the below example I expect the fcn2 to behave in the same way as fcn1:
a = 1;
fcn1 = @(x) x+a;
fcn2 = str2func('@(x) x+a');
fcn1(1)
fcn2(1)
However I am receiving the following error:
??? Undefined function or variable 'a'.
Error in ==> @(x)x+a

Best Answer

When calling STR2FUNC and passing a the name of a variable inside the string that describes the anonymous function this variable will not be defined in the function workspace of STR2FUNC as it was only declared in the MATLAB base workspace.
So instead of passing just the name of the variable:
a = 1;
fcn2 = str2func('@(x) x+a');
You can pass the actual variable and generate the string inside the function, e.g.:
fcn2 = str2func(['@(x) x+' num2str(a)]);