How to execute a function when stored in a variable
3 次查看(过去 30 天)
显示 更早的评论
I am trying to find a way to store instructions on executing a line of code in a variable, so that when a user loads in that variable, they can execute the line of code contained within the variable. A simple example of something I'd like to run is:
sprintf('example %s',localVariable)
So the user's code would look something like:
localVariable = 'foo';
loadedVar = load('file.mat','Var'); %where 'Var' is something along the lines of @eval('sprintf(''example %s'',localVariable)'), but I can't seem to figure out exactly how to do this
a = loadedVar %I think I want loadedVar to be a function handle of some sort, where the function looks at the local workspace for 'localVariable' and constructs a string;
The desired output then when calling 'a' is:
'example foo'
Any ideas on how to accomplish this?
0 个评论
回答(2 个)
Jan
2021-6-29
编辑:Jan
2021-6-29
This is the job of functions. Hiding the function as char vector in a MAT file is too strange to be clear or efficient. Simple store the funtion in an M file and call it.
Do not reinvent Matlab as a programming language based on interpreting the contents of MAT files.
3 个评论
Stephen23
2021-6-29
编辑:Stephen23
2021-6-29
" understand that I can manipulate this in each piece of code that references this variable..."
Passing the required data as input/output arguments would be the best solution.
"...but this would be enormousy tedious!"
It is not "tedious" to pass input/output arguments reliably (in fact it lets you concentrate on more important things).
In contrast the approach you have chosen obfuscates the code intent, and forces you into writing complex, inefficient, slow code which is liable to bugs and difficult to debug. That is a very... interesting design decision.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!