What you want to do is to actually use struct2array
and then flatten the result.
A = reshape(struct2array(test), [], 1);
% 1
% 2
% 3
% 4
% 5
% 6
Benchmark
As a follow-up, I have performed a little bit of a benchmark comparing the usage of struct2cell
to struct2array
. We would expect the cell2mat(struct2cell())
method to be slower because 1) it is operating on cell arrays and 2) it uses cell arrays rather than numerical arrays which are notoriously slow. Here is the script I used to perform the tests.
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
And the results (R2015b)
