首页 > 解决方案 > 有什么有效的方法来识别大数组中的一组 1?

问题描述

我有一个由和link_slots组成的 800 个元素组成1的数组。例如。因此,表示已占用,未占用, 仅用于标记一组 1 的结束。我想知道每组s 的开始和结束索引。例如,在这里,以 开始,以结束。我的代码有效,但通过 Profiler 发现这需要很多时间。有没有有效的方法来解决这个问题?考虑到我必须为大小为 800 个元素的多个数组执行此操作。0-1[1 1 1 -1 0 0 0 0 1 1 -1 0 0 1 1 1 1 -1 0 0 ...]10-11[1,9,14][3,10,17]

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

标签: arraysmatlabindexingwhile-loop

解决方案


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' 的索引的起始索引,其先前的值为 0 或 '-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 ...

推荐阅读