微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从结构字段创建全阶乘抽样的巧妙方法

如何解决从结构字段创建全阶乘抽样的巧妙方法

我在 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'} 
...
...

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

有什么聪明的编码方式?

解决方法

您可以使用 this question 的任何答案来获得数值向量的所有组合。我会将 top answer 定义为函数 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。