Efficiently identifying a set of 1s: follow up question after months later
1 次查看(过去 30 天)
显示 更早的评论
I asked a question that had my working but an inefficient code. It was answered.
The task was to efficiently identify a set of 1s in an array containing 1s,0s and -1. The solution was working when the array was like below
a = [1 1 1 -1 0 0 0 0 1 1 -1 0 0 1 1 1 1 -1 0 0]; %original question array
but now when it is as below, it is unable to identify the indices where a set of 1s start.
a=[1 1 -1 1 1 1 -1 0 0]; % current array
The difference w.r.t the original question array and this current array is only that now, the set of 1s are next to another set of 1s separated by the marker, -1. Whereas in the original question, there were some 0's in between. Can anyone please help me on this or even suggest an answer in alternative to the accepted answer as the task is still the same.
0 个评论
采纳的回答
Stephen23
2021-12-4
编辑:Stephen23
2021-12-4
A simpler, more efficient, much more 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
更多回答(0 个)
另请参阅
类别
在 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!