Concatenating vectors of different length

14 views (last 30 days)
My code will generate two vectors of different sized in a total of 5 iterations.
Iteration 1- Size- 1x18993
Iteration 2- Size- 1x37986
Iteration 3- Size- 1x75972
Iteration 4- Size- 1x151944
Iteration 5- Size- 1x455832
I want to generate a single matrix of size 5x455832 by padding the previous vectors with NaN.
  3 Comments
Dwijaraj
Dwijaraj on 13 Sep 2023
Stephen, I tried using Padcat but the problem arised since it doesnt support anything other than row or column vector.
For eg after iteration 2, my concatenated array is of size 2x37986, and hence this array cannot be used in padcat further to generate the 3x75972 matrix. Hope you understood the problem I faced.
Stephen23
Stephen23 on 13 Sep 2023
Edited: Stephen23 on 13 Sep 2023
"Hope you understood the problem I faced."
Yes, I do understand the problem you faced, which is why in my previous comment I already told you the solution to that problem.
"For eg after iteration 2, my concatenated array is of size 2x37986, "
Nope, that is not what I told you to do. For some reason you apparently tried to call PADCAT repeatedly inside the loop, attempting to concatenate onto the matrix on each loop iteration. That won't work.
This is what I advised you to do (unlike what you tried, this will work):
C = cell(1,N);
for k = 1:N
V = .. your code that generates vector V
C{k} = V;
end
M = padcat(C{:}); % comma-separated list
Much neater, more robust, and likely more efficient than continuously expanding an array inside a FOR loop.

Sign in to comment.

Accepted Answer

Bruno Luong
Bruno Luong on 12 Sep 2023
Edited: Bruno Luong on 12 Sep 2023
result = [];
for k=1:5
veck = randi(10, 1, 2+randi(5))% compute your vector here ..
n = size(veck,2);
result(:,end+1:n) = NaN;
veck(1,n+1:size(result,2)) = NaN;
result(k,:) = veck;
end
veck = 1×7
2 10 1 5 6 6 8
veck = 1×3
6 9 7
veck = 1×3
1 4 7
veck = 1×5
2 4 3 2 10
veck = 1×4
5 2 5 5
result
result = 5×7
2 10 1 5 6 6 8 6 9 7 NaN NaN NaN NaN 1 4 7 NaN NaN NaN NaN 2 4 3 2 10 NaN NaN 5 2 5 5 NaN NaN NaN

More Answers (1)

NAVNEET NAYAN
NAVNEET NAYAN on 12 Sep 2023
You have to change the size of first 4 vectors obtained in the first 4 iterations according to the size of vector 5.
t1=ones(1,18993);
t2=ones(1,37986);
t3=ones(1,75972);
t4=ones(1,151944);
t5=ones(1,455832);
% Now change size of first 4 vectors as following by appending zeros in the
% end or you can pad NaN in the end
t1 = [t1, zeros(1, length(t5) - length(t1))];
t2 = [t2, zeros(1, length(t5) - length(t2))];
t3 = [t3, zeros(1, length(t5) - length(t3))];
t4 = [t4, zeros(1, length(t5) - length(t4))]; % For NaN, replace zeros from NaN
% Now concatenate these changed vectors to form 5x455832 matrix
Tfinal=cat(1,t1,t2,t3,t4,t5);

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!