将任意嵌套的整数数组的结构展平为整数的平面数组

时间:2016-01-11 14:09:27

标签: matlab vector struct flatten

是否可以在Matlab中将一组任意嵌套的整数数组展平为一个整数的平面数组?例如,

[[1,2,[3]],4] -> [1,2,3,4]

任何形式的指导都会有所帮助。谢谢。 例如,

a.c = [5,4];
a.b.a=[9];
a.b.d=[1,2];

a= b: [1x1 struct]
   c: [5 4]

在这种情况下,我的输出将是

output= [9,1,2,5,4]

2 个答案:

答案 0 :(得分:3)

我认为你必须调整文件交换中的flatten函数来使用struct2cell,所以这样的事情:

function C = flatten_struct(A)

    A = struct2cell(A);
    C = [];
    for i=1:numel(A)  
        if(isstruct(A{i}))
            C = [C,flatten_struct(A{i})];
        else
            C = [C,A{i}]; 
        end
    end

end

这导致:

a.c = [5,4];
a.b.a=[9];
a.b.d=[1,2];

flatten_struct(a)

ans =

    5    4    9    1    2

所以顺序是你声明结构的顺序,而不是你的示例顺序,我认为这是按字母顺序排列的。但你可以控制它,所以这应该不是问题。

答案 1 :(得分:-1)

我有一个初步的黑客,它可以工作,但相当笨拙。它以递归方式下降,保存结构名称在每个“级别”解压缩返回的结构。

%  struct2sims converter
function simout = struct2sims(structin)
fnam = fieldnames(structin);
for jf = 1:numel(fnam)
    subnam = [inputname(1),'_',fnam{jf}];
    if isstruct(structin.(fnam{jf}) ) ,
    % need to dive;  build a new variable that's not a substruct
     eval(sprintf('%s = structin.(fnam{jf});', fnam{jf}));
    eval(sprintf('simtmp = struct2sims(%s);',fnam{jf}) );
    % try removing the struct before getting any farther...
    simout.(subnam) = simtmp;
    else
    % at bottom, ok
    simout.(subnam) = structin.(fnam{jf});
    end

end
 %  need to unpack structs here, after each level of recursion
 % returns...
    subfnam = fieldnames(simout);
    for kf = 1:numel(subfnam)
         if isstruct(simout.(subfnam{kf}) ),  
             subsubnam = fieldnames(simout.(subfnam{kf}));
             for fk = 1:numel(subsubnam)
                 simout.([inputname(1),'_',subsubnam{fk}])...
                     = simout.(subfnam{kf}).(subsubnam{fk}) ;
             end
             simout = rmfield(simout,subfnam{kf});
         end
    end
 % if desired write to file with:
 % save('flattened','-struct','simout');
end