# How to find column where 0 turns to 1 for each row

1 回表示 (過去 30 日間)
Tanika Bawa 2022 年 7 月 14 日

Hello!
I would like to be able to find the column (or column title) for each row where the 0 turns to 1.
I have attached example rows (egcolumnsep.mat), so for example for row 5, I would like it to return column 20 (or Bins_11). I would like an output for all the rows though. Some rows might have only 0's (this can be NaN). This basically gives me the reaction time for each row.
Thank you for your help! =)

サインインしてコメントする。

### 採用された回答

Bruno Luong 2022 年 7 月 15 日

c1 = find(strcmp(DATAb1.Properties.VariableNames,'Bins_1')); % == 10
% Extract relevant data
A = table2array(DATAb1(:,c1:end));
if ~all(ismember(A,[0 1]),'all')
error('Data must be 0 or 1')
end
[cols,rows] = find(diff(A.')==1);
cols = cols+c1;
Idx01 = table(rows,cols)
Idx01 = 37×2 table
rows cols ____ ____ 1 468 1 499 1 855 1 890 2 196 3 452 3 487 3 531 3 828 3 860 4 306 4 338 4 370 4 404 4 434 4 468
##### 2 件のコメントなしを表示なしを非表示
Tanika Bawa 2022 年 7 月 15 日
Thank you! Do you know how I could get it so that I only get ther first transition from 0 to 1?
Bruno Luong 2022 年 7 月 15 日

Why didn't tell us that you are interested only the first transition in the question?
You can call this statement after the above scriot
groupsummary(Idx01, 'rows','min')
or start from scratch
c1 = find(strcmp(DATAb1.Properties.VariableNames,'Bins_1')); % == 10
% Extract relevant data
A = table2array(DATAb1(:,c1:end));
if ~all(ismember(A,[0 1]),'all')
error('Data must be 0 or 1')
end
[a,cols] = max(A,[],2);
cols = (cols+c1-1) .* (a==1) % returns 0 if no transition 0->1 is found
cols = 5×1
468 196 452 306 20

サインインしてコメントする。

### その他の回答 (1 件)

Jonas 2022 年 7 月 14 日

yourMat=[0 0 0 0 0;
0 1 1 0 0;
0 0 0 1 0];
where=arrayfun(@(idx)find(diff(yourMat(idx,:))==1,1,'first')+1,1:size(yourMat,1),'UniformOutput',false)'
where = 3×1 cell array
{1×0 double} {[ 2]} {[ 4]}
an empty cell shows that there was not such a change
you could set it to NaN and convert to an normal array by
where{cellfun('isempty',where)}=NaN
where = 3×1 cell array
{[NaN]} {[ 2]} {[ 4]}
where=cell2mat(where)
where = 3×1
NaN 2 4
##### 3 件のコメント1 件の古いコメントを表示1 件の古いコメントを非表示
Jonas 2022 年 7 月 14 日
you can convert your table to a matrix before, e.g. yourTable{:,:} or table2array()
Tanika Bawa 2022 年 7 月 14 日
I did try that and it doesn't really let me do it unfortunately. It gives me this error:
"Unable to concatenate the specified table variables.
Caused by:
Error using categorical/cat (line 56)
Unable to concatenate a double array and a categorical array."
I do need to keep all the columns (because in the end I just want to add a column at the end with the results from this)

サインインしてコメントする。

### カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

R2020b

### Community Treasure Hunt

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

Start Hunting!

Translated by