executing an m-file using a string for calling

Hello, I am trying to find a way to execute an m-file from a string.
For example I get from a DB return the name myfunc(1,2) as a char and I want to execute the function myfunc.m with the (1,2) as variables. Does anyone have any solution.
Thanx in advance.
Georgios Mavropoulos

 Respuesta aceptada

Walter Roberson
Walter Roberson el 3 de Mzo. de 2011
%somehow before this, DBString = 'myfunc(1,2)'
eval(DBString)

7 comentarios

Jan
Jan el 3 de Mzo. de 2011
Although I find arguments against EVAL every day, it is the most exact answer here. +1
Walter Roberson
Walter Roberson el 3 de Mzo. de 2011
There are other possibilities, such as parsing out the arguments and turning them in to a cell array of numbers, and extracting the function name string, and then using feval(FunctionNameString, Args{:})
Thanks for this answer. It just solved my long-term problem
Mathijs Franssen
Mathijs Franssen el 28 de En. de 2021
Dear Jan, given your statement 'Although I find arguments against EVAL every day, it is the most exact answer here. +1', is there any other option nowadays or could you kindly elaborate on the arguments against using eval? Many thanks in advance!
Stephen23
Stephen23 el 28 de En. de 2021
Editada: Stephen23 el 28 de En. de 2021
"...is there any other option nowadays..."
There have always been better options, not just "nowadays".
The fundamental flaw in the original question was not adressed in the thread so far, but is due to the poor data design: storing a function and its inputs in one string. Better data design would store its inputs as data in their own right (which is anyway simpler, is more efficient, and avoids superfluous, slow, lossy data type conversion). Then calling the function/script is trivial with one str2func call and then more efficient calling of the function handle thereafter.
"...could you kindly elaborate on the arguments against using eval?"
In this particular example, repeated calls to eval this string will likely be less efficient than repeated calls to the equivalent function handle (MATLAB's JIT compiler has no way to optimize the code hidden in a string, but it certainly can with a properly defined function handle called with properly defined input arguments).
On top of this we have the usual problems of disabling the static code analysis (which means no syntax checking, no tracing variables, no code hints, no tab completion, no input hints, no variable highlighting, etc.), makes debugging harder, is a security risk, and various other points that have been discussed many times before (quite easy to find by searching this forum).
Mathijs Franssen
Mathijs Franssen el 18 de Feb. de 2021
Excellent, thanks a million Stephen! Wasn't aware of str2func, first time I've ran into this sort of issue. This helps!
Jürgen
Jürgen el 30 de Nov. de 2021
for me 'Stephens comment' of 28th,jan. 2021 should be worked out more compact and moved to the top-rated answer to the question.
I was also searching for something like (list of) function reference defined during runtime.
The str2fun seems the way to go with respect to all the points in Stephens comment (code analysis, syntax checking, tracing variables, code hints, tab completion, input hints, variable highlighting, debugging, security).

Iniciar sesión para comentar.

Más respuestas (4)

Jan
Jan el 17 de Mzo. de 2011
If you call RUN with a string, which contains the path, the file extension .m is removed. Without the path, .m is kept.
mfile = dir('layer*.m');
[trash, name] = fileparts(mfile(1).name);
run(name);
Or:
mfile = dir('layer*.m');
run(fullfile(cd, mfile(1).name));
Note: "mfile(1)" considers, that DIR can find multiple matching files.
Georgios Mavropoulos
Georgios Mavropoulos el 3 de Mzo. de 2011

0 votos

thank you Walter, I tried both of your suggestions and they both worked.
Thanks again for the help.
Dimitris
Dimitris el 15 de Mzo. de 2011
I'm trying to do something similar. My output is an .m file. Like this:
mfile = dir('layer*.m')
So, afterwards I want to run the file named layer<something>.m But if I do as you say:
eval(mfile.name)
I get this error:
??? Undefined variable "layer2" or class "layer2.m".
Why is this happening? The file I'm trying to run, layer2.m, is in the current directory.

3 comentarios

Walter Roberson
Walter Roberson el 15 de Mzo. de 2011
You have to remove the .m suffix before you can eval()
As you do not appear to be sending input or expecting output, it is plausible that you are using scripts instead of functions. If so, then consider using run(), as that will remove the .m for you.
Jan
Jan el 17 de Mzo. de 2011
RUN removes the file extension only, if the name contains the path:
working: run('C:\MFiles\layer2.m')
failing: run('layer2.m')
I think, this is a bug in RUN: If "script" does not contain a path, "exist(script, 'file')" checks the existence before "evalin('caller', [script, ';'])". But if "script" is an existing file, the file extension let EVALIN fail. "evalin('caller', [s, ';'])" would work. (checked in 2009a)
Jan
Jan el 17 de Mzo. de 2011
Bug report is submitted.

Iniciar sesión para comentar.

Dimitris
Dimitris el 15 de Mzo. de 2011
I tried to use:
run(mfile.name)
but I got the same error:
??? Undefined variable "layer2" or class "layer2.m".
Error in ==> run at 74
evalin('caller',[script ';']);
:S I also tried
run(eval(mfile.name))
with the same results... Thank you for your interest!

2 comentarios

You can try using
eval(mfile.name)
Jan
Jan el 12 de Nov. de 2017
@Hayatullahi Adeyemo: The variable "mfile.name" contains the string 'layer2'. The error message produced by run('layer2') means, that there is no function with this name in Matlab's path. Then eval('layer2') will not work also.

Iniciar sesión para comentar.

Categorías

Más información sobre Debugging and Analysis en Centro de ayuda y File Exchange.

Preguntada:

el 3 de Mzo. de 2011

Comentada:

el 30 de Nov. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by