Executing eval in function handle ?
古いコメントを表示
I have the following code which does not work and I don't understand why:
foo='name'
name='C23';
handle=@(var) eval(var)
handle(foo)
I get the following error:
Error using eval
Undefined function or variable 'name'.
Error in @(var)eval(var)
Here,
handle(foo)
should return
'C23'
Can someone tell me what I did wrong and how to make this work?
Thanks in advance
3 件のコメント
Rik
2018 年 3 月 18 日
I can't see any direct reason why this doesn't work, however, why do you want to do this? There is almost always a very good replacement for eval. Usually eval solves problems caused by bad data management. Instead of learning how a mop works, it's usually beter to close the faucet.
In other words: what is your goal? Maybe we can help you solve that instead of this question.
Stephen23
2018 年 3 月 19 日
"I could not think of any other way to do this"
Using eval is rarely the solution that beginners think it is: it will just make your code slow, complex, and (as you are finding out now) much buggier and harder to debug. Read this to know more:
採用された回答
その他の回答 (1 件)
Greg
2018 年 3 月 19 日
1 投票
Most importantly! respond to Rik's comment above. The use of eval is very nearly always a horrible idea.
However, to your question: it does not work because the scope of name is where the anonymous function is defined. When executing the anonymous function, name is out of scope in that workspace.
1 件のコメント
Greg
2018 年 3 月 19 日
I hesitate to mention it could work if you used evalin('caller',...); but again, bad idea!
カテゴリ
ヘルプ センター および File Exchange で Variables についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!