How to execute a function when stored in a variable
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Jan
am 29 Jun. 2021
Bearbeitet: Jan
am 29 Jun. 2021
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 Kommentare
Stephen23
am 29 Jun. 2021
Bearbeitet: Stephen23
am 29 Jun. 2021
" 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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!