vec2mat w/ different number of columns

后端 未结 2 1208
礼貌的吻别
礼貌的吻别 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:57

    You can employ bsxfun's masking capability here -

    %// 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
    

    Code run -

    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
    

提交回复
热议问题