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

9 visualizzazioni (ultimi 30 giorni)
Jaya il 4 Dic 2021
Modificato: Stephen23 il 4 Dic 2021
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 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Stephen23 il 4 Dic 2021
Modificato: Stephen23 il 4 Dic 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
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Jaya il 4 Dic 2021
Thanks a lot!

Accedi per commentare.

### Categorie

Scopri di più su Matrix Indexing in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by