How to extract column index based on value in another column?
7 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Star Strider
2023 年 2 月 21 日
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 件のコメント
その他の回答 (1 件)
Voss
2023 年 2 月 21 日
% 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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Calendar についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!