2012-10-05 32 views
2

我有几个MatLab功能,并且几乎所有功能都有测试功能。是不是真的有一个命名约定,现在测试功能,所以我最终FunctionName_Testtest_functionName功能,tests_functionName,等MatLab - 基于他们的名字执行功能

Howerver,我看到两件事情,这些功能的共同点:

  • 该名称包含“测试”(具有不同的外壳)。
  • 它们没有输入或输出参数。

我想写一个函数,可以在给定的文件夹(或路径)下找到所有尊重这两个条件并执行它们的函数。这样我就可以在一次调用中执行我所有的测试功能。

有什么办法可以做到吗?

回答

3

你可以做如下:

fun=dir('*test*.m'); %% look for matlab scripts which name contains 'test' 
fun={fun.name};  %% extract their names 
fun=fun(cellfun(@(x) (nargin(x)==0),fun)); %% select the ones with no input arguments 
fun = regexprep(fun, '.m', ''); % remove '.m' from the filenames 
cellfun(@eval,fun); %% execute them 
+0

+1好答案!但它也会给你FooTestBar.m。不知道OP是否需要它 –

+0

@Andrey,你是对的...... – Oli

+0

必须有一个正则表达式,只在最后或开始时给出'test'。像“test * | * test”。我的正则表达式技能是生锈的:) –

1

首先,让你的文件夹下的所有文件:

d = dir(myFolder); 

删除那些延伸不.m

indexes = strcmp('.m',{d.ext}); 
    d(indexes) = []; 

然后,把他们所有的名字:

fileNames = {d.Name}; 

检查哪一个开始或结束测试:

testPrefix = strncmp('test',fileNames) 
    testPostfix = %# Left as an exercise to the reader 
    sutiableFileNames = fileNames(testPrefix | testPostfix); 

现在你可以使用`nargin'检查的参数量:

numOfInParams = cellfun(@nargin,sutiableFileNames); 
    numOfOutParams = cellfun(@nargout,sutiableFileNames); 

然后再过滤器(我想你已经得到了主意)