Efficiently identifying a set of 1s: follow up question after months later

1 visualización (últimos 30 días)
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.

Respuesta aceptada

Stephen23
Stephen23 el 4 de Dic. de 2021
Editada: Stephen23 el 4 de Dic. de 2021
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

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by