combine vectors in different length in to one matrix

120 views (last 30 days)
hello, I want to combine 100 row vectors in different lengths in to one big matrix, say:
v1 = [1 2 3]; v2 = [1 2 3 4]; v3 = [1]; ....; vn = [xx xx xx ... xx];
A = [1 2 3 0 0; 1 2 3 4 0; 1 0 0 0 0; xx xx xx xx xx];
I want to find the max length in these row vectors, say 5, then if the length of the other vector is smaller than 5, then we set 0 in the rest position, how can I do that?
Thanks!

Accepted Answer

Simon Allosserie
Simon Allosserie on 6 Apr 2022
You can combine vectors of different lengths in cell arrays, instead of adding zeros to your vectors. It will be easier to process them also, because then they are together in one structure that you can loop through (instead of having to acces each vector v1, v2, ... separately). See https://nl.mathworks.com/help/matlab/ref/cell.html
If you however per se want to put them together with a lot of zeros, I'd suggest something like this:
First find the maximum vector length, let's call it maxLength;
Then define a matrix A sized (n, maxLength) with n the number of vectors you have
A = zeros(n, maxLength);
Then add your vectors to A one by one like
A(i,1:lengthVi) = vi;
Hope this helps.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!