有什么有效的方法可以识别大数组中的一组 1?

Any efficient way to identify a set of 1s in a big array?

我有一个名为 link_slots 的数组,包含 800 个元素,由 10-1 组成。 例如。 [1 1 1 -1 0 0 0 0 1 1 -1 0 0 1 1 1 1 -1 0 0 ...]。因此,1 表示占用,0 表示未占用,-1 只是标记一组 1 的结束。 我想知道每组 1 的开始和结束索引。例如,这里以 [1,9,14] 开始,以 [3,10,17] 结束。我的代码可以运行,但通过 Profiler 发现它需要花费大量时间。有什么有效的方法可以解决这个问题吗?考虑到我必须为大小为 800 个元素的多个数组执行此操作。

i=1;
while(i<numel(link_slots(1,:)) ) %to cycle through whole array
    j=i
    if(link_slots(1,i)==1)  %i.e. if occupied 
        startt(i)=i %store it in the start array
        j=i
        while(link_slots(index,j+1)~=-1) 
            j=j+1
        end
        endd(i)=j  %store the end index upon encountering -1
    end
    i=j+1
end
data= [1 1 1 -1 0 0 0 0 1 1 -1 0 0 1 1 1 1 -1 0 0]';

结束索引很容易找到:

I=find(data==-1);
end_indices=I-1;

找到您想要的起始索引 '1' 的索引,其先前值为零或 '-1' 例如:

temp=[0;data]; % i added a zero to the start of data to use diff function 
I=find(diff(temp)>0 & data==1) % here diff function calculates difference between subsequent values of array. so in case of your question if we had ..0 1..diff is 1 and ...