find '1' in an array
Afficher commentaires plus anciens
hi ı wanna ask question about find a 1's number in array. for example the array should be like that 1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 1 and ı only want to find a group of 1's. In array 0 1 0 or 1 0 1 or 0 0 0 1 0 something like that is an error in array. How can we do that. thanks
Réponses (5)
Guillaume
le 1 Oct 2015
If you mean you want to find the start of the sequences of at least two consecutive 1, then it's simple using diff. You'll find the start of a sequence when the diff with the previous value is 1 (transition from 0 to 1), and you'll know it's followed by a 1 when the diff with the next value is 0, so:
A = [1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 1]
startseq1 = find(A & diff([0 A]) == 1 & diff([A 0]) == 0)
4 commentaires
ali
le 1 Oct 2015
Note that if you want the find the end of the groups and extract them, it's pretty much the same:
A = [1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 1];
startseq1 = find(A & diff([0 A]) == 1 & diff([A 0]) == 0); %is 1, preceded by 0, followed by another 1
endseq1 = find(A & diff([A 0]) == -1 & diff([0 A]) == 0); %is 1, followed by 0, preceded by 1
sequences = arrayfun(@(s,e) A(s:e), startseq1, endseq1, 'UniformOutput', false)
ali
le 1 Oct 2015
Guillaume
le 1 Oct 2015
I have no idea what you mean. The code I've written work:
>>A = [1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 1];
>>startseq1 = find(A & diff([0 A]) == 1 & diff([A 0]) == 0)
startseq1 =
1 7 13
>>endseq1 = find(A & diff([A 0]) == -1 & diff([0 A]) == 0)
endseq1 =
3 9 16
>>sequences = arrayfun(@(s,e) A(s:e), startseq1, endseq1, 'UniformOutput', false);
>>celldisp(sequences)
sequences{1} =
1 1 1
sequences{2} =
1 1 1
sequences{3} =
1 1 1 1
Andrei Bobrov
le 1 Oct 2015
[ii,~,~,v] = regexp(sprintf('%d',x(:)'),'1(1+)')
Jan
le 1 Oct 2015
data = [1 1 1 0 1 0 1 1 1 0 1 0 1 1 1 1];
[b, n] = RunLength(data);
result = sum(b == 1 & n > 1);
If the data are small (e.g. just some kB), or you do not have a compiler installed already, use RunLength_M instead from the same submission.
ali
le 2 Oct 2015
0 votes
Catégories
En savoir plus sur Resizing and Reshaping Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!