MATLAB: How to combine random size arrays in one matrix – in a loop

combine vector matrix unequal length looppadcat

Hey, I've been able to find a lot of solutions for my matlab program on this site but the next problem still goes unanswered.
I have a loop in which every run a vector is created with a random size. After the loop is finished I want all these vectors presented in a matrix with each vector as a column. How can I do this? The shorter vectors may either be filled with NaN's or zero's.
In essence the program looks like this:
for i=1:1:10;
l=ceil(rand(1)*10);
vector=rand(l,1);
end
matrix=[vector1 vector2 ... vector10 ];
Thanks in advance for helping me out.

Best Answer

Hello Jeroen,
  • Generate the vectors - I'll call them b - in your for-loop and keep track of the longest vector that is generated in the loop. Store the vectors as a matrix: b(:,ii).
  • Once done, initialize a 0-matrix A using zeros(M,N) where M is equal to the size of the longest vector and N is the total number of vectors.
  • Lastly run another for-loop to paste into the matrix the individual vectors using something like:
A(:,ii) = [b(:,ii); zeros(length(A(1,:)) - length(b(:,ii)),1)]
where ii is the running index of the loop.
You can also get this done using only one loop, of course, by simply concatenating vectors that have been "filled up" with the adequate number of 0s, or filling up the existing matrix before concatenating.
Related Question