vec2mat w /列数不同

时间:2015-01-19 14:25:25

标签: matlab matrix reshape

参考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个项并把它们放进去,然后用剩下的2个空单元填充0。所以ncols = [4 6 6]。遗憾的是vet2mat不允许将vector作为列号。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以使用accumarray

A = [4 9 8 9 6 1 8 9 7 7 7 4 6 2 7 1].'; %'// data
ncols = [4 6 6]; %// columns
n = max(ncols);
cs = cumsum(ncols);
ind = 1;
ind(cs+1) = 1;
ind = cumsum(ind(1:end-1)); %// `ind` tells the row for each element of A
result = accumarray(ind(:), A(:), [], @(x) {[x; zeros(n-numel(x),1)]}); %// split `A` as 
    %// dictated by `ind`, and fill with zeros. Each group is put into a cell.
result = [result{:}].'; %'// concatenate all cells