combine vectors in different length in to one matrix

103 次查看(过去 30 天)
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!

采纳的回答

Simon Allosserie
Simon Allosserie 2022-4-6
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by