将任意嵌套的整数数组的结构展平为整数的平坦数组 [英] flatten a struct of arbitrarily nested arrays of integers into a flat array of integers

查看:79
本文介绍了将任意嵌套的整数数组的结构展平为整数的平坦数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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,4]

任何一种指导都将有所帮助.谢谢. 例如,

Any kind of guidance will be helpful. Thanks. For example,

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

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

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

In this case, my output will be

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

推荐答案

我认为您必须适应

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

结果是:

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.

这篇关于将任意嵌套的整数数组的结构展平为整数的平坦数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆