Function that runs all functions in a directory

18 views (last 30 days)
Hello all,
I want to write a function that loops through all the functions in a given directory and runs them.
For each specific function, I have a variable called FunInputs that tells me what the argument is for each function. For example, the input argument for the function titled 'A' is '930'.
FunInputs=
{'A','930';'B','804';'C','812';'D','830';'E','811';'F','827';'G','931';'H','932';'I','800';'J','814';'K','805';'L','1012';'M','933';'N','820';'O','1010';'P','802';}
In addition, all functions in the directory share the input 'FileCode'. So, when I run function 'A' it looks like:
output = A('FileCode','930');
I'm feeling really lost as to how to go about writing a function that can automatically process my list of functions according to their specific inputs (sorry....I'm a newbie!)
this is what I have so far...
function [AllFunOutputs] = RunAllFuns(FileCode, FunInputs)
files = what('\MATLAB\Funs');
% get all file names in directory 'Funs'
funsExist = files(arrayfun(@(f) isMatFun(f), files));
% make sure the files in the directory are functions
funNames = arrayfun(@(f) {stripDotM(f)}, funsExist);
% strip the '.m' suffix from all file names
% below, match the function name with its argument
k = 1;
for i=1:length(FunInputs)
if(strncmp(FunInputs(i,1),files,1)== 1))
funNames(k,1) = FunInputs(i,2);
k = k+1;
end
end
AllFunOutputs = cellfun(@(f) {executeStrAsFun(char(f), T)}, funNames);
% run the files as functions and combine the results in a matrix
end
function [AllFunOutputs] = executeStrAsFun(fname, FileCode, FunInput)
try
fun = str2func(fname); % convert string to a function
results = fun(FileCode,FunInput); % 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
Thank you so much in advance for your time, help, and consideration!!!!!
  1 Comment
Matt Kindig
Matt Kindig on 25 Oct 2012
This looks good to me. What doesn't work about this code? Please clarify.

Sign in to comment.

Accepted Answer

Jan
Jan on 26 Oct 2012
A simpler method to get the function names:
fileDir = dir(\Matlab\Funs\*.m');
fileName = {fileDir.name};
funcName = strrep(fileName, '.m', '');
I do not understand the line:
if (strncmp(FunInputs(i,1),files,1)== 1))
files is an array, therefore the output of strncmp will be an array also. Then an any or all would be smarter, because if requires a scalar condition such that all is applied implicitely. But why do you compare the first character?
feval might be easier than converting the string to a function handle at first.

More Answers (0)

Categories

Find more on File Operations 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!