count groups of elements and distances between them

조회 수: 2 (최근 30일)
VT
VT 2013년 8월 8일
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.

채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 8월 9일
편집: Andrei Bobrov 2013년 8월 9일
A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0];
a = A == 6 | A == 0;
a1 = [0 a(:)' 0];
i1 = strfind(a1,[0 1]);
i2 = strfind(a1,[1 0]);
L = i2 - i1;
D = i1(2:end) - i2(1:end-1);
or
A= [6 6 6 4 4 4 4 4 6 5 5 7 7 7 8 9 8 7 0 0 0 0];
a = [A(:) == 6 | A(:) == 0 ; false];
b = [true;diff(a(:))~=0];
bn = find(b);
idx = bn(cumsum(a(b))>0);
LD = diff(idx);
L = LD(1:2:end);
D = LD(2:2:end);

추가 답변 (3개)

Richard Brown
Richard Brown 2013년 8월 8일
편집: Richard Brown 2013년 8월 8일
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
Richard Brown
Richard Brown 2013년 8월 8일
Ah, I thought I'd corrected it fast enough that noone would notice. Sorry about that.
Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 9일
I 've made some speed test, Richards code is the fastest

댓글을 달려면 로그인하십시오.


Azzi Abdelmalek
Azzi Abdelmalek 2013년 8월 8일
편집: Azzi Abdelmalek 2013년 8월 9일
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
VT 2013년 8월 9일
Colleagues. Thank you for the fast response. Especially, I like the simplicity of codes without a need to create loops.

카테고리

Help CenterFile Exchange에서 Financial Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by