I'm very new to Matlab and I'm looking for some advice from someone who is more experienced.
I want to write a function that will loop through a given directory and run all matlab functions in that directory. What is the best/most robust way to do this? I've provided my implementation below but, I'm worried because most of my matlab experience thus far tells me that for every function I implement, there is usually an equivalent matlab built-in or at least a better/faster/safer way to achieve the same ends.
I'd be happy to provide any other necessary info. Thanks!
function [results] = runAllFiles(T)
files = dir('mydir/');
% get all file names in mydir
funFile = files(arrayfun(@(f) isMatFun(f), files));
% prune the above list to get a list of files in dir where isMatFun(f) == true
funNames = arrayfun(@(f) {stripDotM(f)}, funFiles);
% strip the '.m' suffix from all the file names
results = cellfun(@(f) {executeStrAsFun(char(f), T)}, funNames);
% run the files as functions and combine the results in a matrix
end
function [results] = executeStrAsFun(fname, args)
try
fun = str2func(开发者_JAVA百科fname); % convert string to a function
results = fun(args); % run the function
catch err
fprintf('Function: %s\n', err.name);
fprintf('Line: %s\n', err.line);
fprintf('Message: %s\n', err.message);
results = ['ERROR: Couldn''t run function: ' fname];
end
end
Well, for looking up all the .m-files in a directory, you can make use of files = what('mydir/');
and then consult files.m
to get all .m-files (including their extension). At first sight, I would use eval
to evaluate each function, but on the other hand: your solution of using str2func
looks even better.
So I guess you could do the following:
function [results] = runAllFiles(T)
files = what('mydir/');
mFiles = arrayfun(@(f) {stripDotM(f)}, files.m);
% strip the '.m' suffix from all the file names
results = cellfun(@(f) {executeStrAsFun(char(f), T)}, mFiles);
% run the files as functions and combine the results in a matrix
end
function [results] = executeStrAsFun(fname, args)
try
fun = str2func(fname); % convert string to a function
results = fun(args); % run the function
catch err
fprintf('Function: %s\n', err.name);
fprintf('Line: %s\n', err.line);
fprintf('Message: %s\n', err.message);
results = ['ERROR: Couldn''t run function: ' fname];
end
end
A problem I foresee is when you have both functions and scripts in your directory, but I know of no (built-in) way to verify whether an .m-file is a function or a script. You could always check the contents of the file, but that might get somewhat complicated.
精彩评论