vec2mat w /列数不同

gme*_*oni 2 matlab matrix reshape

参考reshape row wise w /不同的开始/结束元素数 @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
Run Code Online (Sandbox Code Playgroud)

我只拿了A的前4个项并把它们放进去,然后用剩下的2个空单元填充0.所以ncols = [4 6 6].不幸的是vet2mat,不允许矢量作为列号.

有什么建议?

Div*_*kar 5

你可以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
Run Code Online (Sandbox Code Playgroud)

代码运行 -

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
Run Code Online (Sandbox Code Playgroud)