# combine vectors in different length in to one matrix

96 views (last 30 days)
yuh zhang on 6 Apr 2022
Commented: yuh zhang on 8 Apr 2022
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!
yuh zhang on 8 Apr 2022

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);
A(i,1:lengthVi) = vi;
Hope this helps.
Stephen23 on 6 Apr 2022

### Categories

Find more on Matrix Indexing in Help Center and File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by