首页 > 解决方案 > 从结构字段创建全因子采样的巧妙方法

问题描述

我在 MATLAB 中有(例如)这个结构数组

g=struct();
g.var1=[0,1,2];
g.var2=[5,6,7];
g.var3={'a','b','c'};
...

我想创建一个单元格数组,对所有字段一一采样(网格网格)

想要一个单元阵列;

M×N 元胞数组

{[0]}    {[5]}    {'a'} 
{[0]}    {[5]}    {'b'} 
{[0]}    {[5]}    {'c'} 
{[1]}    {[5]}    {'a'} 
{[1]}    {[5]}    {'b'} 
{[1]}    {[5]}    {'c'} 
{[2]}    {[5]}    {'a'} 
{[2]}    {[5]}    {'b'} 
{[2]}    {[5]}    {'c'} 
{[0]}    {[6]}    {'a'} 
{[0]}    {[6]}    {'b'} 
{[0]}    {[6]}    {'c'} 
{[1]}    {[6]}    {'a'} 
{[1]}    {[6]}    {'b'} 
{[1]}    {[6]}    {'c'} 
...
...

我希望我的代码适用于所有一般情况,例如只有一个字段或多个字段的输入结构。

对此进行编码的聪明方法是什么?

标签: matlabstructcombinations

解决方案


您可以使用此问题的任何答案来获取数字向量的所有组合。我会将最佳答案定义为函数getIndices,并使用输出索引对您的通用结构进行操作g

您必须进行的唯一额外处理是让数字数组和单元数组放置得很好,我只是添加了一个isnumeric检查以进行相应的转换。

flds = fieldnames( g ); % get structure fields
% Get indices of fields (1:n for each field) and get combinations
idx = cellfun( @(fld) 1:numel(g.(fld)), flds, 'uni', 0 );
idx = getIndices( idx );
% Create output
out = cell(size(idx,1),numel(flds));
for ii = 1:numel(flds)
    if isnumeric( g.(flds{ii}) )
        out(:,ii) = num2cell( g.(flds{ii})(idx(:,ii)) );
    else
        out(:,ii) = g.(flds{ii})(idx(:,ii));
    end
end

function combs = getIndices( vectors )
    % Source: https://stackoverflow.com/a/21895344/3978545
    n = numel(vectors); %// number of vectors
    combs = cell(1,n); %// pre-define to generate comma-separated list
    [combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two
    %// comma-separated lists is needed to produce the rows of the result matrix in
    %// lexicographical order 
    combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
    combs = reshape(combs,[],n); %// reshape to obtain desired matrix
end

推荐阅读