Efficient colon operator for multiple start and end points

后端 未结 4 1721
我寻月下人不归
我寻月下人不归 2020-12-06 13:21

Suppose I have the following two variables:

start_idx = [1 4 7];
end_idx   = [2 6 15];

I want to efficiently (no for loop

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 13:51

    As I indicated in the comments, a one liner to solve this would be :

    out=cell2mat(arrayfun(@(x,y)[x:y],start_idx,end_idx,'uniformoutput',false));
    

    The arrayfun call will create a cell array whose each cell is a part of your output :

    ans =
    
         1     2
    
    
    ans =
    
         4     5     6
    
    
    ans =
    
      Columns 1 through 8
    
         7     8     9    10    11    12    13    14
    
      Column 9
    
        15
    

    By wrapping it inside a cell2mat call you get the expected output :

    out =
    
      Columns 1 through 8
    
         1     2     4     5     6     7     8     9
    
      Columns 9 through 14
    
        10    11    12    13    14    15
    

提交回复
热议问题