m-files as function inputs in for loop
Show older comments
Hi everyone!
I have a function.m that I run with an input.m like this:
function input
I'm trying to process a Monte Carlo Samples in this function. So I have a lot of m-files inputs: input_1.m, input_2.m, ..., input_n.m.
To process everything I set up this for loop:
for i = 1:n
filename = sprintf('%s_%d', 'input', i);
function filename
end
But the function doesn't recognize the string to run. The errors are:
Error using pdatvp_seq (line 49)
Data file not found: filename.
Error in run_test (line 4)
function filename
Someone knows how to help me to do the function recognize the string to run?
4 Comments
Matt J
on 5 Feb 2018
Bad idea creating a file called "function.m". "function" is a reserved MATLAB keyword.
Sarah Andrade
on 6 Feb 2018
What does progcoll look like? I'm not familiar with trying to just pass one .m file in after another like that. Usually you would pass in arguments in parentheses. Also, trying to simplify your question is good, but doing so by replacing real function names with 'function' is very confusing since it is a fundamental key word.
Sarah Andrade
on 6 Feb 2018
Edited: Sarah Andrade
on 6 Feb 2018
Accepted Answer
More Answers (1)
Kai Domhardt
on 6 Feb 2018
As a general description, you have a function you want to call in an .m file:
.m
function out = target_fun(in)
...
end
main.m
fun_call = [fun_name, '(' fun_param ')'];
result = eval(fun_call);
For your use you can apply it like this:
for i = 1:n
filename = sprintf('%s_%d', 'input', i);
eval(filename)
end
3 Comments
Do NOT use eval to call a script/function! Using eval is massive overkill for the simple running of a script/function. Also, depending on what objects the compiler matches that string to (or what is contained in the string) there could be all sorts of unpredictable side effects and bugs: using eval is not a robust solution, and will increase the chance of bugs (and makes them harder to locate).
for k = 1:n
name = sprintf('name_%d', k);
run(name)
end
Note that run accepts an absolute/relative path, so those files can be anywhere on your computer/drives (and not just on the MATLAB path).
Functions: If you need to call multiple functions in a loop (optionally with any required input/output arguments) then use str2func:
for k = 1:n
fun = str2func(sprintf('name_%d', k));
[...] = fun(...);
end
PS: calling a script/function still does not answer the question. The problem lies elsewhere!
Sarah Andrade
on 6 Feb 2018
Greg
on 15 Feb 2018
I just want to re-iterate:
Categories
Find more on Monte Carlo Analysis in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!