Count and "synchronize" events in several columns

조회 수: 1 (최근 30일)
Fabs
Fabs 2016년 8월 31일
답변: Azzi Abdelmalek 2016년 8월 31일
Y'all,
sorry if the question doesn't fully capture the actual problem, I simply don't know how to exactly describe it in a concise manner. This is the problem: I have a matrix consisting of columns with occurrences of 1s (the first column is simply a time counter). Each series of 1s without an NaN in between is an "event". Like this:
1 NaN NaN NaN
2 NaN NaN NaN
3 1 NaN NaN
4 1 1 NaN
5 NaN NaN NaN
6 NaN NaN NaN
7 NaN 1 NaN
8 1 1 NaN
9 1 NaN 1
10 1 NaN 1
11 NaN NaN NaN
12 1 1 NaN
13 1 1 NaN
14 NaN NaN NaN
15 NaN 1 NaN
16 NaN 1 1
A total of three events in column 2, four events in column 3, and two events in column 4 (again, column 1 is a time step/counter). I need to count the number of events and match them up with the respective events in the other columns. The end result should look like this:
1 NaN NaN NaN NaN
2 NaN NaN NaN NaN
3 1 NaN NaN 1
4 1 1 NaN 1
5 NaN NaN NaN NaN
6 NaN NaN NaN NaN
7 NaN 1 NaN 2
8 1 1 NaN 2
9 1 NaN 1 2
10 1 NaN 1 2
11 NaN NaN NaN NaN
12 1 1 NaN 3
13 1 1 NaN 3
14 NaN NaN NaN NaN
15 NaN 1 NaN 4
16 NaN 1 1 4
Any input appreciated! Oh, the actual matrix consists of more than 3 columns with events (for now there are 4 columns, but it will get extended to about 15 eventually).
Thanks, F

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 8월 31일
편집: Andrei Bobrov 2016년 8월 31일
A1=A(:,2:end);
A1= any(~isnan(A1),2);
out1 = bwlabel(A1);
out1(~out1) = nan;
out = [A,out1];
or
A1=A(:,2:end);
A1= any(~isnan(A1),2);
out1 = cumsum([false;diff(A1)==1]).*A1;
out1(~out1) = nan;
out = [A,out1];

추가 답변 (2개)

Azzi Abdelmalek
Azzi Abdelmalek 2016년 8월 31일
A=[1 NaN NaN NaN
2 NaN NaN NaN
3 1 NaN NaN
4 1 1 NaN
5 NaN NaN NaN
6 NaN NaN NaN
7 NaN 1 NaN
8 1 1 NaN
9 1 NaN 1
10 1 NaN 1
11 NaN NaN NaN
12 1 1 NaN
13 1 1 NaN
14 NaN NaN NaN
15 NaN 1 NaN
16 NaN 1 1]
idx=any(A(:,2:end)==1,2)'
ii1=strfind([0 idx],[0,1])
ii2=strfind([idx 0],[1,0])
c=nan(size(A,1),1)
for k=1:numel(ii1)
c(ii1(k):ii2(k))=k
end
out=[A c]
  댓글 수: 1
Fabs
Fabs 2016년 8월 31일
This works! Thanks, Azzi! I accepted Andrei's answer for the lack of a loop, though. (unfortunately I can't accept two answers...)

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


Azzi Abdelmalek
Azzi Abdelmalek 2016년 8월 31일
idx=any(A(:,2:end)==1,2)'
[~,~,ii]=unique(nonzeros(cumsum(~idx).*idx))
c=nan(size(A(:,1)))
c(logical(idx))=ii
out=[A c]

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by