首页 文章

Matlab:在函数/脚本中运行给定目录中的所有函数

提问于
浏览
3

我是Matlab的新手,我正在寻找一些经验丰富的人的建议 .

我想编写一个循环遍历给定目录并运行该目录中所有matlab函数的函数 . 这样做的最佳/最强大的方法是什么?我在下面提供了我的实现,但是我很担心,因为到目前为止我的大部分matlab经验告诉我,对于我实现的每个函数,通常都有一个内置的等效matlab或至少更好/更快/更安全的方式达到同样的目的 .

我很乐意提供任何其他必要的信息 . 谢谢!

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(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

1 回答

  • 3

    好吧,为了查找目录中的所有.m文件,您可以使用 files = what('mydir/'); 然后查阅 files.m 以获取所有.m文件(包括其扩展名) . 乍一看,我会使用 eval 来评估每个函数,但另一方面:使用 str2func 的解决方案看起来更好 .

    所以我想你可以做到以下几点:

    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
    

    我预见到的一个问题是你的目录中有两个函数和脚本,但我知道没有(内置)方法来验证.m文件是函数还是脚本 . 您可以随时检查文件的内容,但这可能会有些复杂 .

相关问题