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

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

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

问题描述

在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]

推荐答案

我认为您必须适应 flatten 函数从文件交换中使用 struct2cell 像这样:

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.

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

08-29 02:27