MATLAB repeat numbers based on a vector of lengths

后端 未结 6 1204
失恋的感觉
失恋的感觉 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:27

    result = zeros(1,sum(input_lengths));
    result(cumsum([1 input_lengths(1:end-1)])) = 1;
    result = cumsum(result);
    

    This should be pretty fast. And memory usage is the minimum possible.

    An optimized version of the above code, due to Bentoy13 (see his very detailed benchmarking):

    result = zeros(1,sum(input_lengths));
    result(1) = 1;
    result(1+cumsum(input_lengths(1:end-1))) = 1;
    result = cumsum(result);
    

提交回复
热议问题