【发布时间】:2019-06-03 12:20:58
【问题描述】:
这是All possible combinations of many parameters MATLAB问题的后续
除了我的参数集的所有可能组合之外,我还有一个条件参数。例如,只有当参数 'corrAs' 设置为 'objective' 时,我才需要包含名为 'lambda' 的参数。
做到这一点,现在我正在做以下事情
%% All posible 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'};
% If corrAs is 'objective', then also set lambda
params.lambda = {0.01, 0.1, 1, 10, 100};
%%%%%%%%%%%%% The solution posted on the link %%%%%%%%%%%
%% Get current parameter and evaluate
fields = fieldnames(params);
nFields = numel(fields);
sz = NaN(nFields, 1);
% Loop over all parameters to get sizes
for jj = 1:nFields
sz(jj) = numel( params.(fields{jj}) );
end
% Loop for every combination of parameters
idx = cell(1,nFields);
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:nFields
%%%%%%%%%%% My addition for conditional parameter %%%%%%%%%%%
% lambda is valid only when corrAs is 'objective'
if isfield(currentParam, 'corrAs') && strcmp(fields{jj}, 'lambda') && ~strcmp(currentParam.corrAs, 'objective')
continue;
end
currentParam.(fields{jj}) = params.(fields{jj}){idx{jj}};
end
%% Do something with currentParam
end
它可以工作,但是即使 corrAs 不是“客观的”,主 for 循环的迭代次数也包括 lambda 参数。因此,我最终使用相同的 currentParam 进行了多次评估。
我怎样才能更有效地做到这一点?
【问题讨论】:
标签: matlab struct combinations