我有一个参数列表,我需要在此列表中评估我的方法.现在,我这样做
% Parameters
params.corrAs = {'objective', 'constraint'};
params.size = {'small', 'medium', 'large'};
params.density = {'uniform', 'non-uniform'};
params.k = {3,4,5,6};
params.constraintP = {'identity', 'none'};
params.Npoints_perJ = {2, 3};
params.sampling = {'hks', 'fps'};
% Select the current parameter
for corrAs_iter = params.corrAs
for size_iter = params.size
for density_iter = params.density
for k_iter = params.k
for constraintP_iter = params.constraintP
for Npoints_perJ_iter = params.Npoints_perJ
for sampling_iter = params.sampling
currentParam.corrAs = corrAs_iter;
currentParam.size = size_iter;
currentParam.density = density_iter;
currentParam.k = k_iter;
currentParam.constraintP = constraintP_iter;
currentParam.Npoints_perJ = Npoints_perJ_iter;
currentParam.sampling = sampling_iter;
evaluateMethod(currentParam);
end
end
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
我知道它看起来很难看,如果我想添加一个新类型的参数,我必须编写另一个for循环.有什么办法,我可以把它变成这个吗?或者也许使用2 for循环而不是那么多.
我尝试了以下但是,它不会导致我需要的东西.
for i = 1:numel(fields)
% if isempty(params.(fields{i}))
param.(fields{i}) = params.(fields{i})(1);
params.(fields{i})(1) = [];
end
Run Code Online (Sandbox Code Playgroud)
您需要的是输入参数的所有组合.不幸的是,随着您添加更多参数,存储需求将快速增长(并且您将不得不使用大型索引矩阵).
相反,这里是一个使用(从未创建)n1*n2*...*nm
矩阵的线性指标的想法,其中ni
是每个字段中元素的数量,对于m
字段.
它足够灵活,可以应对任何数量的字段params
.没有经过性能测试,尽管与任何"所有组合"操作一样,当你添加更多字段时params
,你应该警惕计算时间的非线性增加,注意prod(sz)
!
我所展示的代码很快,但性能完全取决于你在循环中执行的操作.
% Add parameters here
params.corrAs = {'objective', 'constraint'};
params.size = {'small', 'medium', 'large'};
params.density = {'uniform', 'non-uniform'};
% Setup
f = fieldnames( params );
nf = numel(f);
sz = NaN( nf, 1 );
% Loop over all parameters to get sizes
for jj = 1:nf
sz(jj) = numel( params.(f{jj}) );
end
% Loop for every combination of parameters
idx = cell(1,nf);
for ii = 1:prod(sz)
% Use ind2sub to switch from a linear index to the combination set
[idx{:}] = ind2sub( sz, ii );
% Create currentParam from the combination indices
currentParam = struct();
for jj = 1:nf
currentParam.(f{jj}) = params.(f{jj}){idx{jj}};
end
% Do something with currentParam here
% ...
end
Run Code Online (Sandbox Code Playgroud)
旁白: