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

1 回表示 (過去 30 日間)
Jaya
Jaya 2021 年 12 月 4 日
編集済み: Stephen23 2021 年 12 月 4 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by