How can I pass a workspace variable as a parameter to STR2FUNC in MATLAB 7.11 (R2011a)?
2 views (last 30 days)
Show older comments
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
Accepted Answer
MathWorks Support Team
on 29 Jun 2011
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)]);
0 Comments
More Answers (0)
See Also
Categories
Find more on Function Handles 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!