arrays - 有什么有效的方法来识别大数组中的一组 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 ...]
1
0
-1
1
[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
解决方案
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 ...
推荐阅读
- php - 为什么我的干净 url 在另一个文件夹中不起作用?
- python - 即使通过 Django 中间件重定向后请求仍继续
- tcl - 如何将包含单个正斜杠的网络文件路径作为参数传递给 tcl proc?
- amazon-web-services - 将数据从 AWS Glue 数据目录提取到外部文本文件
- node.js - 如何在没有 root 的情况下从 Ubuntu 18.04.3 中完全删除节点?
- flutter - 如何在颤动中显示小吃吧无限持续时间?
- javascript - 如何在 JS FETCH API 之外访问返回值
- python - 如何解决与在 Windows 10 上安装 dlib 相关的问题?
- c# - HashSet 重叠不能按预期工作
- netlogo - 如何让Netlogo模型自动停止,关闭文件并重新启动模型