Any efficient way to identify a set of 1s in a big array?
2 次查看(过去 30 天)
显示 更早的评论
I have an array called link_slots of 800 elements made of 1, 0 and -1.
E.g. 1 1 1 -1 0 0 0 0 1 1 -1 0 0 1 1 1 1 -1 0 0 .... So, 1 denotes occupied, 0 for unoccupied and -1 just to mark the end of a set of 1s.
I want to know the start and end indices of each set of 1s. E.g.,here, start as [1,9,14] and end as [3,10,17]. My code works but found out through Profiler that it takes a lot of time. Is there any efficient way to solve this? Considering that I have to do this thing for multiple arrays for size 800 elements.
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
0 个评论
采纳的回答
Stephen23
2021-12-4
编辑:Stephen23
2021-12-6
A simple, efficient, robust solution:
a = [1,1,1,-1,0,0,0,0,1,1,-1,0,0,1,1,1,1,-1,0,0];
d = diff([false,a==1,false]);
s = find(d>0) % start
e = find(d<0)-1 % end
And tested on your new data set:
a = [1,1,-1,1,1,1,-1,0,0];
d = diff([false,a==1,false]);
s = find(d>0) % start
e = find(d<0)-1 % end
更多回答(1 个)
Ive J
2021-9-3
Try this
a = [1 1 1 -1 0 0 0 0 1 1 -1 0 0 1 1 1 1 -1 0 0];
astart = [1, 9, 14];
astop = [3, 10, 17];
dda = diff([0, 0, diff(a)]);
start = find(dda == 1);
if a(1) > 0
start = [1, start];
end
stop = find(circshift(a < 0, -1));
all(astart == start)
all(astop == stop)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!