flatten a struct of arbitrarily nested arrays of integers into a flat array of integers

前端 未结 2 1616
余生分开走
余生分开走 2021-01-20 04:22

Is it possible to flatten an array of arbitrarily nested arrays of integers into a flat array of integers in Matlab? For example,

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


        
2条回答
  •  隐瞒了意图╮
    2021-01-20 04:32

    I think you will have to adapt the flatten function from the file exchange to use struct2cell so something like this:

    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
    

    This results in:

    a.c = [5,4];
    a.b.a=[9];
    a.b.d=[1,2];
    
    flatten_struct(a)
    
    ans =
    
        5    4    9    1    2
    

    So the order is in the order you declared your struct instead of in your example order which I presume is alphabetical. But you have control over this so it shouldn't be a problem.

提交回复
热议问题