MATLAB repeat numbers based on a vector of lengths

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

    More of a comment than anything, but I did some tests. I tried a for loop, and an arrayfun, and I tested your for loop and arrayfun version. Your for loop was the fastest. I think this is because it is simple, and allows the JIT compilation to do the most optimisation. I am using Matlab, octave might be different.

    And the timing:

    Solution:     With JIT   Without JIT  
    Sam for       0.74       1.22    
    Sam arrayfun  2.85       2.85    
    My for        0.62       2.57    
    My arrayfun   1.27       3.81    
    Divakar       0.26       0.28    
    Bentoy        0.07       0.06    
    Daniel        0.15       0.16
    Luis Mendo    0.07       0.06
    

    So Bentoy's code is really fast, and Luis Mendo's is almost exactly the same speed. And I rely on JIT way too much!


    And the code for my attempts

    clc,clear
    input_lengths = randi(20,[1 10000]);
    
    % My for loop
    tic()
    C=cumsum(input_lengths);
    D=diff(C);
    results=zeros(1,C(end));
    results(1,1:C(1))=1;
    for i=2:length(input_lengths)
        results(1,C(i-1)+1:C(i))=i*ones(1,D(i-1));
    end
    toc()
    
    tic()
    A=arrayfun(@(i) i*ones(1,input_lengths(i)),1:length(input_lengths),'UniformOutput',false);
    R=[A{:}];
    toc()
    

提交回复
热议问题