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.

采纳的回答

Stephen23
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
s = 1×3
1 9 14
e = find(d<0)-1 % end
e = 1×3
3 10 17
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
s = 1×2
1 4
e = find(d<0)-1 % end
e = 1×2
2 6

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by