引用Reshape row wise w/ different starting/ending elements number @Divakar提供了一个很好的解决方案,但是,如果列数不总是相同怎么办?
样品运行-
>> A'
ans =
4 9 8 9 6 1 8 9 7 7 7 4 6 2 7 1
>> out
out =
4 9 8 9 0 0
6 1 8 9 7 7
7 4 6 2 7 1
我只提取了A的前4个项,然后将它们放进去,然后用0填充其余2个空单元格。所以
ncols = [4 6 6]
。不幸的是,vet2mat
不允许将矢量作为列号。有什么建议?
最佳答案
您可以在此处使用bsxfun
的屏蔽功能-
%// Random inputs
A = randi(9,1,15)
ncols = [4 6 5]
%// Initialize output arary of transposed size as compared to the desired
%// output arary size, as we need to insert values into it row-wise and MATLAB
%// follows column-major indexing
out = zeros(max(ncols),numel(ncols));
mask = bsxfun(@le,[1:max(ncols)]',ncols); %//'# valid positions mask for output
out(mask) = A; %// insert input array elements
out = out.' %//'# transpose output back to the desired output array size
代码运行-
A =
5 3 7 2 7 2 4 6 8 1 9 7 5 4 5
ncols =
4 6 5
out =
5 3 7 2 0 0
7 2 4 6 8 1
9 7 5 4 5 0