MATLAB: Count and “synchronize” events in several columns

event counter

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

Best Answer

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];