Efficient colon operator for multiple start and end points

后端 未结 4 1730
我寻月下人不归
我寻月下人不归 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 14:07

    This is cumbersome, but perhaps faster:

    x = min(start_idx):max(end_idx);
    m = sum(bsxfun(@ge,x,start_idx(:)),1)==numel(end_idx)-sum(bsxfun(@le,x,end_idx(:)),1)+1;
    result = x(m);
    

    It correctly handles empty ranges, i.e.

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

    gives

    result =
         1     2     4     5     6
    

提交回复
热议问题