MATLAB Answers

extracting index number if an item exist in some columns while not in the rest columns

28 views (last 30 days)
mirewuti muhetaer
mirewuti muhetaer on 27 Mar 2020 at 0:21
Commented: mirewuti muhetaer on 27 Mar 2020 at 18:12
Hi,
let us say, i have a data table which has following form:
Index name A1 A2 A3,,,,,A10
and there is an item called David. The interesting things is David is in some of the columns (david is not A1, A2 columns and is in the rest of the columns).
I am interesed in the extracting the index number of david whether is in column or not (if not in the column, may return o or NaN), i tried hard, but could not write the corresponding code, can some one help?
Thanks.

  4 Comments

Show 1 older comment
Akira Agata
Akira Agata on 27 Mar 2020 at 4:13
You mean, you have something like the following table
T =
4×6 table
A1 A2 A3 A4 A5 A6
__________ __________ __________ __________ __________ __________
{'David' } {'Bowie' } {0×0 char} {0×0 char} {0×0 char} {0×0 char}
{0×0 char} {0×0 char} {0×0 char} {0×0 char} {'David' } {0×0 char}
{0×0 char} {0×0 char} {'David' } {0×0 char} {0×0 char} {'Bowie' }
{0×0 char} {0×0 char} {0×0 char} {'Bowie' } {0×0 char} {0×0 char}
...and want to find the column which contains 'David' ( A1, A3, and A5 in the above example) ?

Sign in to comment.

Accepted Answer

Akira Agata
Akira Agata on 27 Mar 2020 at 8:04
OK. Then, the solution would be like this:
% Sample table
Name = {'David','Bowie','Lynch','Mirewuti','Muhetaer','Akira','Agata'};
rng('default'); % for reproducability
T = table(Name(randperm(7,6))',Name(randperm(7,6))',Name(randperm(7,6))',Name(randperm(7,6))',...
'VariableNames',{'A1','A2','A3','A4'});
% Find the column which contains 'David'
idx = strcmp(T{:,:},'David');
idx = any(idx);
% Return the column name
colName = T.Properties.VariableNames(idx);
[Sample Table]
>> T
T =
6×4 table
A1 A2 A3 A4
____________ ____________ ____________ ____________
{'Lynch' } {'Akira' } {'Muhetaer'} {'Lynch' }
{'Bowie' } {'Bowie' } {'David' } {'Mirewuti'}
{'Mirewuti'} {'Mirewuti'} {'Bowie' } {'Akira' }
{'David' } {'Muhetaer'} {'Lynch' } {'Agata' }
{'Akira' } {'Lynch' } {'Akira' } {'David' }
{'Agata' } {'Agata' } {'Mirewuti'} {'Muhetaer'}
[Extracted column name]
>> colName
colName =
1×3 cell array
{'A1'} {'A3'} {'A4'}

More Answers (0)

Sign in to answer this question.

Tags