MATLAB Answers

Concatenate arrays within a loop,

423 views (last 30 days)
Vasishta Bhargava
Vasishta Bhargava on 30 Jun 2018
Edited: Stephen Cobeldick on 30 Jun 2018
I would like to concatenate arrays inside a loop.. how can I do it ?

  0 Comments

Sign in to comment.

Answers (1)

Stephen Cobeldick
Stephen Cobeldick on 30 Jun 2018
Edited: Stephen Cobeldick on 30 Jun 2018
Easy, given any number of arrays in a cell array C. You could use a loop like this, although it is inefficient because the output array is not preallocated:
C = {[1,2],[3,4],...} % cell array of arrays.
A = C{1};
for k = 2:numel(C)
A = [A;C{k}];
end
Simpler and more efficient would be to concatenate them all at once, without a loop, e.g.:
A = vertcat(C{:})
Whatever you do, do NOT try to access variable names dynamically in a loop! Read this to know why:
Using an array (e.g. a cell array) and indexing is much simpler, neater, much more efficient, less buggy, and easier to debug.

  0 Comments

Sign in to comment.

Sign in to answer this question.


Translated by