Sort the rows of a table based on row entries in two columns of another table

6 次查看(过去 30 天)
I am trying to sort the rows in one table (Tright) based on the order in which the rows are present in another table (Tleft)
Tright ->
EndNodes_1 EndNodes_2 var1
__________ __________ _____________
{'1' } {'5' } 4
{'10'} {'3' } 1
{'2' } {'11'} 6
{'2' } {'8' } 2
{'3' } {'14'} 9
Tleft ->
EndNodes_1 EndNodes_2
__________ __________
{'1' } {'5' }
{'2' } {'8'}
{'2' } {'11' }
{'3' } {'14'}
{'10'} {'3' }
Expected output:
T =
EndNodes_1 EndNodes_2 var1
__________ __________ _____________
{'1' } {'5' } 4
{'2' } {'8' } 2
{'2' } {'11'} 6
{'3' } {'14'} 9
{'10'} {'3' } 1
I tried the following,
T = innerjoin(Tleft,Tright)
[~, index] = sort_nat(T.EndNodes_1);
T = T(index,:)
Obtained result:
T ->
EndNodes_1 EndNodes_2 var1
__________ __________ _____________
{'1' } {'5' } 4
{'2' } {'11'} 6
{'2' } {'8' } 2
{'3' } {'14'} 9
{'10'} {'3' } 1
Any suggestions on how to obtain the expected output will be really helpful.
Code:
ar = {'1' '10' '2' '2' '3'};
br = {'5' '3' '11' '8' '14'};
cr = [4 1 6 2 9];
Tright = table(ar',br',cr','VariableNames',{'EndNodes_1','EndNodes_2','var1'})
al = {'1' '2' '2' '3' '10'};
bl = {'5' '8' '11' '14' '3'};
Tleft = table(al',bl','VariableNames',{'EndNodes_1','EndNodes_2'})
T = innerjoin(Tleft,Tright);
[~, index] = sort_nat(T.EndNodes_1);
T = T(index,:)

采纳的回答

Samatha Aleti
Samatha Aleti 2020-2-25
Hi,
According to my understanding you are trying to arrange the table “Tright” columns in the order of table ‘”Tleft”.
You can use “ismember” to do this as follows:
EndNodes_1 = {'1';'10';'2';'2';'3'};
EndNodes_2 = {'5';'3';'11';'8';'14'};
var1 = [4; 1; 6; 2; 9];
Tright = table(EndNodes_1, EndNodes_2, var1)
t1= table(EndNodes_1, EndNodes_2);
EndNodes_1 = {'1';'2';'2';'3';'10'};
EndNodes_2 = {'5';'8';'11'; '14';'3'};
Tleft = table(EndNodes_1, EndNodes_2)
t2 = Tleft;
[Lt2,Loct1] = ismember(t2, t1, 'rows');
Tright = Tright(Loct1,:)

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Descriptive Statistics and Visualization 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by