Search code examples
arraysmatlaboptimizationcell-array

Efficient concatenation of multiple, varying in size matrices in a loop


I would like to efficiently concatenate multiple matrices into a vector. However, the number of such matrices and their sizes vary. Say, I have two stacks A and B, each consisting of m matrices.

Naive approach would be the following:

merged = [];
for i = 1 : m
    merged = [merged ; A{i}(:) ; B{i}(:)];
end

The challenging part is to optimise the above code to avoid copying the older array contents to the new array as it makes each assignment. For instance, one could compute the number of elements in each matrix and then preallocate a vector capable of storing all the elements. Still, I am not entirely sure how to efficiently place the matrices inside the vector.

Any suggestions would be appreciated.


Solution

  • One possible approach:

    merged = cellfun(@(x) x(:), [A(:) B(:)].', 'uni', false);
    merged = vertcat(merged{:});