count groups of elements and distances between them
Afficher commentaires plus anciens
Dear, Colleagues:
Let's say I have a matrix:
A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0]
I would like to count number of six and number of zeros (as a group of consequent elements).
And, I would also like to know the distance between groups.
The Matlab output that I would like to get: _____________________________________________________________________________
There are two groups of 6 and one group of 0s.
L= [3 1 4] - length of each group
D= [5 9] - distance between groups
Thank you in advance.
Réponse acceptée
Plus de réponses (3)
Richard Brown
le 8 Août 2013
Modifié(e) : Richard Brown
le 8 Août 2013
A = [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0];
x = diff([find(diff([0 ismember(A, [0 6]) 0]))]);
L = x(1:2:end);
D = x(2:2:end);
7 commentaires
Azzi Abdelmalek
le 8 Août 2013
What if
A= [5 6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0 0 1];
Richard Brown
le 8 Août 2013
Still works fine ...
Azzi Abdelmalek
le 8 Août 2013
>> L
L =
1 5 9
>> D
D =
3 1 4
L should be [3 1 5]
Richard Brown
le 8 Août 2013
I think you've typed it in wrong ... if I run it on your A I get L = [3 1 5], D = [5 9]
Azzi Abdelmalek
le 8 Août 2013
I copied your, code, maybe before you edited it.
Richard Brown
le 8 Août 2013
Ah, I thought I'd corrected it fast enough that noone would notice. Sorry about that.
Azzi Abdelmalek
le 9 Août 2013
I 've made some speed test, Richards code is the fastest
Azzi Abdelmalek
le 8 Août 2013
Modifié(e) : Azzi Abdelmalek
le 9 Août 2013
A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0];
A=num2str(A);
A(A==' ')='';
[a0,a1,group0]=regexp(A,'[06]+','start','end','match');
longueur=a1-a0+1 % length of groups
id=diff(sort([a0 a1 ]))-1 ;
id=id(2:2:end)% distance between groups
group0 % your groups
%or with Richard's idea
idx=1:numel(A)+2;
A=A~=0 & A~=6 ;
id=diff(idx(~~(diff([0 ~A 0]))));
L1=id(1:2:end);
D1=id(2:2:end);
VT
le 9 Août 2013
0 votes
Catégories
En savoir plus sur Structures 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!