필터 지우기
필터 지우기

How do I find the duration of a number in an array?

조회 수: 1 (최근 30일)
Joe
Joe 2015년 5월 28일
댓글: Joe 2015년 5월 28일
Given the array
c=[3 3 3 5 5 6 7 8 1 1 3 3 3 0 0 0 4 4 4 5 6 7 8 3 3 3 9 10 3];
I am trying to find the average duration of each number in this array. For example, I am looking to find the average duration for 3 in this array. I know that 3 occurs 10 times but is grouped into 4 separate occurrences. I want the output to be the average duration for 3...which is 2.5. please help!

채택된 답변

Andrei Bobrov
Andrei Bobrov 2015년 5월 28일
편집: Andrei Bobrov 2015년 5월 28일
c = c(:);
ii = [true;diff(c)~=0];
i2 = diff([find(ii);numel(ii)+1]);
[a,b,c0] = unique(c(ii),'first'); % in new version of MATLAB:
[~,jj] = sort(b); %
[~,j1] = sort(jj); % [a1,~,c1] = unique(c(ii),'stable');
a1 = a(jj); %
c1 = j1(c0); %
out = [a1,accumarray(c1,i2,[],@mean)];
or with sorting
ii = [true;diff(c)~=0];
i2 = diff([find(ii);numel(ii)+1]);
[a,~,c0] = unique(c(ii));
out1 = [a,accumarray(c0,i2,[],@mean)]
  댓글 수: 2
Joe
Joe 2015년 5월 28일
It worked thanks!
Joe
Joe 2015년 5월 28일
I am applying this to my data set and the inputs range from 1-10. However, if there are no occurrences of an input (example= there is no 2 in the data set above how can I make sure the output array will have a zero in the place of the 2 or any other number in the series? Is there a way to output a c(2,10) array with c(1,10) being equal to 1:10 and the c(2,10) array being filled with the output values for average duration. if there are none I would want an empty place value to be filled with a zero.

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 5월 28일
c=[3 3 3 5 5 6 7 8 1 1 3 3 3 0 0 0 4 4 4 5 6 7 8 3 3 3 9 10 3];
[ii,jj,kk]=unique(c)
d=accumarray(kk,1)
for k=1:numel(ii)
a=ii(k)
res(k)=d(k)/numel(strfind([0 c==a 0],[0,1]))'
end
out=[ii' res']

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by