From a string to function handle of a function handle
Show older comments
Hi,
Is it possible to transform a string into a function handle calling another function handle?
More specifically, consider the following simple example
func1=@(x)mean(x)
tmp='@(x)func1(x)+3'
we know that defining
func2=str2func(tmp)
does not work.
Is there any way to create a function handle using tmp that will work?
Thanks
Accepted Answer
More Answers (1)
Walter Roberson
on 19 Jul 2017
tmp='@(x)feval(evalin(''caller'',''func1''),x)+3'
2 Comments
Patrick Mboma
on 19 Jul 2017
Walter Roberson
on 19 Jul 2017
The basic issue is that str2func() is operating in a context outside your current workspace, so it does not have access to any variables in your workspace. evalin('caller') gives it that access. You would have the same difficulty with a plain variable:
>> A = 5
A =
5
>> tmp = '@(x) x+A'
tmp =
'@(x) x+A'
>> func2 = str2func(tmp)
func2 =
function_handle with value:
@(x)x+A
>> func2(7)
Undefined function or variable 'A'.
Error in @(x)x+A
str2func always does textual substitutions.
Categories
Find more on Data Type Identification 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!