From a string to function handle of a function handle

조회 수: 3 (최근 30일)
Patrick Mboma
Patrick Mboma 2017년 7월 19일
댓글: James Tursa 2017년 7월 20일
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

채택된 답변

James Tursa
James Tursa 2017년 7월 19일
func2 = eval(tmp);
  댓글 수: 2
Walter Roberson
Walter Roberson 2017년 7월 19일
... risky
James Tursa
James Tursa 2017년 7월 20일
Yep, agreed. If you don't know where that string is coming from and what could be in it or don't trust the source, then eval should probably be avoided.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2017년 7월 19일
tmp='@(x)feval(evalin(''caller'',''func1''),x)+3'
  댓글 수: 2
Patrick Mboma
Patrick Mboma 2017년 7월 19일
Thanks Walter, I guess this would work but at the same time it looks like a very cumbersome way of going about it especially if you have long expressions.
Walter Roberson
Walter Roberson 2017년 7월 19일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Install Products에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by