MATLAB repeat numbers based on a vector of lengths

后端 未结 6 1208
失恋的感觉
失恋的感觉 2021-02-08 09:32

Is there a vectorised way to do the following? (shown by an example):

input_lengths = [ 1 1 1 4       3     2   1 ]
result =        [ 1 2 3 4 4 4 4 5 5 5 6 6 7 ]         


        
6条回答
  •  花落未央
    2021-02-08 10:16

    This is a slight variant of @Daniel's answer. The crux of this solution is based on that solution. Now this one avoids repmat, so in that way it's little-more "vectorized" maybe. Here's the code -

    selector=bsxfun(@le,[1:max(input_lengths)]',input_lengths); %//'
    V = bsxfun(@times,selector,1:numel(input_lengths)); 
    result = V(V~=0)
    

    For all the desperate one-liner searching people -

    result = nonzeros(bsxfun(@times,bsxfun(@le,[1:max(input_lengths)]',input_lengths),1:numel(input_lengths)))
    

提交回复
热议问题