连接结构元素

时间:2016-06-01 00:54:25

标签: matlab matlab-struct

例如

test = struct('one', [1;2;3], 'two', [4;5;6]);

我想垂直连接struct test中的向量。例如,如果它被定义为单元格数组而不是test = {[1;2;3], [4;5;6]},我可以vertcat(test{:})。但是,如果vertcat(test{:})是结构,则struct会返回test个对象。

我希望有一个解决方案,不涉及使用struct2cell创建临时单元格数组。

2 个答案:

答案 0 :(得分:5)

您要做的是实际使用struct2array,然后展平结果。

A = reshape(struct2array(test), [], 1);

%   1
%   2
%   3
%   4
%   5
%   6

基准

作为后续行动,我执行了一些基准测试,比较struct2cellstruct2array的使用情况。我们期望cell2mat(struct2cell())方法更慢,因为1)它在单元阵列上操作,2)它使用单元数组而不是数字数组,这是众所周知的慢。这是我用来执行测试的脚本。

function tests()
    sizes = round(linspace(100, 100000));

    times1 = zeros(size(sizes));
    times2 = zeros(size(sizes));

    for k = 1:numel(sizes)
        sz = sizes(k);
        S = struct('one', rand(sz, 1), 'two', rand(sz, 1));
        times1(k) = timeit(@()cellbased(S));
        times2(k) = timeit(@()arraybased(S));
    end

    figure;
    plot(sizes, cat(1, times1 * 1000, times2 * 1000));
    legend('struct2cell', 'struct2array')
    xlabel('Number of elements in S.a and S.b')
    ylabel('Execution time (ms)')
end

function C = cellbased(S)
    C = cell2mat(struct2cell(S));
end

function C = arraybased(S)
    C = reshape(struct2array(S), [], 1);
end

结果(R2015b)

enter image description here

答案 1 :(得分:0)

在我的情况下,我设法使用:

cell2mat(struct2cell(test))