MATLAB: Storing vectors of different length in one single vector

for loopvaluevectorvectors

Hello, hope you can help me out here…
I have a for-loop which produces with every loop a vector of values. The vectors it produces can have different lengths (for example, the vector in the first round has 10 values, in the second round 15, in the third 2…). In the end I'd like to store the values of these vectors in one single vector, but i really don't know how to best do it.
Thanks a lot in advance!

Best Answer

The slow way:
x = [];
for i = 1:100
y = rand(1, floor(rand*11));
x = [x, y]; % or x = cat(2, x, y)
end
Now the vector x grows in every iteration. Therefore memory for a new vector must be allocated and teh old values are copied.
Filling a vector, cleanup afterwards:
x = nan(100, 10);
for i = 1:100
n = floor(rand*11);
y = rand(1, n);
x(i, 1:n) = y;
end
x(isnan(x)) = []; % Now x is a column vector
Collect the vectors in a cell at first:
C = cell(1, 100);
for i = 1:100
C{i} = rand(1, floor(rand*11));
end
x = cat(2, C{:});
The overhead for creating the CELL is much smaller than the slow method of the growing array.
And if you the array is very large and the section is time-consuming, it matters that cat seems to have problem with a proper pre-allocation internally. Then FEX: Cell2Vec is more efficient.