How to sort all rows in one table based on one row from the table and another table

조회 수: 5 (최근 30일)
I have two different tables one with names (table 1) and others with names and data (table 2) but the second table is out of order. I want to order the names in table 2 by the order in table 1 but also not lose the data in the row. For example:
Table 1: Table 2:
Mom Sister 25 67 89
Dad Mom 88 76 23
Sister Dad 90 45 28
and I want to sort it according to table 1 so
Sister 25 67 89
Mom 88 76 23
Dad 90 45 28
  댓글 수: 1
Stephen23
Stephen23 2022년 8월 22일
t1 = table({'Mom';'Dad';'Sister'},'VariableNames',{'Names'})
t1 = 3×1 table
Names __________ {'Mom' } {'Dad' } {'Sister'}
t2 = table({'Sister';'Mom';'Dad'},[25;88;90],[67;76;45],[89;23;28],'VariableNames',{'Names','Var1','Var2','Var3'})
t2 = 3×4 table
Names Var1 Var2 Var3 __________ ____ ____ ____ {'Sister'} 25 67 89 {'Mom' } 88 76 23 {'Dad' } 90 45 28
t3 = join(t1,t2) % the simple MATLAB approach
t3 = 3×4 table
Names Var1 Var2 Var3 __________ ____ ____ ____ {'Mom' } 88 76 23 {'Dad' } 90 45 28 {'Sister'} 25 67 89

댓글을 달려면 로그인하십시오.

채택된 답변

Voss
Voss 2022년 8월 19일
편집: Voss 2022년 8월 19일
t1 = table( ...
{'Mom';'Dad';'Sister'}, ...
'VariableNames',{'Names'})
t1 = 3×1 table
Names __________ {'Mom' } {'Dad' } {'Sister'}
t2 = table( ...
{'Sister';'Mom';'Dad'}, ...
[25;88;90], ...
[67;76;45], ...
[89;23;28], ...
'VariableNames',{'Names','Var1','Var2','Var3'})
t2 = 3×4 table
Names Var1 Var2 Var3 __________ ____ ____ ____ {'Sister'} 25 67 89 {'Mom' } 88 76 23 {'Dad' } 90 45 28
[~,idx] = ismember(t1.Names,t2.Names);
t2 = t2(idx,:)
t2 = 3×4 table
Names Var1 Var2 Var3 __________ ____ ____ ____ {'Mom' } 88 76 23 {'Dad' } 90 45 28 {'Sister'} 25 67 89

추가 답변 (1개)

KSSV
KSSV 2022년 8월 19일
Read about ismember
T1 = {'Mom', 'Dad' 'Sister'} ;
T2 = {'Sister', 'Mom', 'Dad'};
[c,ia] = ismember(T1,T2) ;
T2(ia)
ans = 1×3 cell array
{'Mom'} {'Dad'} {'Sister'}
Now use the indices ia to reorder your table. For a table T, you can use
T = T(ia,:)

카테고리

Help CenterFile Exchange에서 Tables에 대해 자세히 알아보기

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by