Concatenating vectors of different length

14 次查看(过去 30 天)
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 个评论
Dwijaraj
Dwijaraj 2023-9-13
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 2023-9-13
编辑:Stephen23 2023-9-13
"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.

请先登录,再进行评论。

采纳的回答

Bruno Luong
Bruno Luong 2023-9-12
编辑:Bruno Luong 2023-9-12
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

更多回答(1 个)

NAVNEET NAYAN
NAVNEET NAYAN 2023-9-12
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);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by