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 个评论
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
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
result
0 个评论
更多回答(1 个)
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!