How to extract column index based on value in another column?
7 views (last 30 days)
Show older comments
Anastasiia Khibovska
on 21 Feb 2023
Commented: Star Strider
on 28 Feb 2023
Hi everyone,
I have a table with 5 columns:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1302590/image.png)
I want to create a new column (6th) where each row value corresponds to the value of the first 4 columns (1:4) where the number from column 5 is in.
So for example row 1:
value of column 5 is 2, and present in column 1, so value of column 6 should be 1, and so forth (2,4,1,3,2,1).
I apologize if my question is confusing and very much appreciate your time and help!
0 Comments
Accepted Answer
Star Strider
on 21 Feb 2023
Try something like this —
A = [2 4 1 3 2; 3 1 4 2 3; 2 4 1 3 4; 4 2 3 1 4; 1 3 2 4 4];
T1 = array2table(A, 'VariableNames',{'tar1','tar2','tar3','tar4','probe'})
Col6 = arrayfun(@(k)find(T1{k,1:4}==T1{k,5}), 1:size(T1,1)).';
T1 = addvars(T1,Col6,'After',5)
.
2 Comments
More Answers (1)
Voss
on 21 Feb 2023
% first I create a table of random data
n_rows = 15;
data = zeros(n_rows,4);
for ii = 1:n_rows
data(ii,:) = randperm(4);
end
t = array2table([data randi(4,n_rows,1)], ...
'VariableNames',{'tar1','tar2','tar3','tar4','probe'})
% now construct the new column
n_rows = size(t,1);
new_col = zeros(n_rows,1);
for ii = 1:n_rows
[~,new_col(ii)] = ismember(t{ii,5},t{ii,1:4});
end
t.new_column = new_col
0 Comments
See Also
Categories
Find more on Calendar in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!