vec2mat w/ different number of columns

后端 未结 2 1245
礼貌的吻别
礼貌的吻别 2021-01-21 23:24

Referring to Reshape row wise w/ different starting/ending elements number @Divakar came with a nice solution but, what if the number of columns is not always the same?<

2条回答
  •  醉酒成梦
    2021-01-21 23:52

    You could use accumarray for that:

    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
    

提交回复
热议问题