MATLAB: How to evaluate all the functions that I have in a directory automatically

functions

Hello Everyone,
I have a "n" number of functions with different names in a specific directory "C:\my\path\". I would like to figure out the most efficient way to evaluate all the functions that I have . I know I can use a function handler, but still I am not sure how can I read all the files in the given directory, and the pass each of them as an argument for evaluation purpose.
I've considereing something as below code, but not sure how to read all the functions that i have in a directory.
A=randi(65535,1, 5e6);B=randi(65535,1, 5e6);
numberFunctions = x; %this value is determined by the total number of files in a given path
for k=numberFunctions:%number of Functions
fx = @( ?? ) %Here, how can I read all the files?
C = fx (A, B) %Here, x will go from 1 to n, so I can evaluate all my functions.
end
Thanks,
Francisco

Best Answer

" I know I can use a function handler, but still I am not sure how can I read all the files in the given directory, and the pass each of them as an argument for evaluation purpose."
Assuming you've already got a list of paths to your functions saved as string in a cell array, you can loop through that cell array and apply the following example for each function.
% Example function
fullfileStr = 'C:\my\path\myFunction.m';
% Open and read the m file, then close it.
fid = fopen(fullfileStr);
t = textscan(fid, '%s', 'Delimiter', '\n', 'CommentStyle','%');
fclose(fid);
% find first row that starts with the word "function"
funcRow = find(~cellfun(@isempty, regexp(t{:}, 'function.+')),1);
% Extract the text from the "function" row
funcStr = t{1}{funcRow};
% Remove the 'function' word and any comments on that line;
funcStr = strrep(funcStr, 'function', '');
funcStr = regexprep(funcStr, '%.+', '');
% If there are outputs, remove everying left of equal sign (including equal sign)
funcStr = regexprep(funcStr, '.+=', '');
% If there are inputs, remove anything between the parentheses, including parens.
funcStr = regexprep(funcStr, '\(.+\)', '');
% remove leading/trailing white space
funcStr = strtrim(funcStr);
% convert to function handle
funcHand = str2func(funcStr);