Build a matrix by comparing two other matrices

1 次查看(过去 30 天)
I have two matrices, A (500 x 60) and B (600 x 60). From these I want to create a third matrix, C.
C is made up of all the rows of B in which the values of the first three columns match the values of the first three columns of a row in A. The rows in C need to be ordered the same as A, so when finished the first three columns of A and C will be identical.
Two simplifying facts: 1) The set of values in the first three columns of each row is unique. 2) Each row in A has a match in B.
A simplified example:
A = [ 1 2 3 5 5 5; 2 3 4 6 6 6; 3 4 5 7 7 7; 4 5 6 8 8 8; 5 6 7 9 9 9]
B = [ 2 3 4 1 1 1; 2 3 5 6 6 6; 1 2 3 2 2 2; 4 5 6 3 3 3; 4 5 7 1 1 1; 3 4 5 4 4 4; 5 6 7 4 4 4 ]
C = [ 1 2 3 2 2 2; 2 3 4 1 1 1; 3 4 5 4 4 4; 4 5 6 3 3 3; 5 6 7 4 4 4]
As you can see, the rows from B whose first three values match the first three of a row in A have been added to C, and ordered in the same row-order as A. Any rows in B whose first three values don’t match the first three in A have been discarded.
Does anybody know some fairly painless way to do this? BTW, computation time isn’t an issue, since I only have to do it once or twice.
Thank you in advance!!!

采纳的回答

Roger Stafford
Roger Stafford 2014-3-19
[t,loc] = ismember(A(:,1:3),B(:,1:3),'rows');
C = B(loc(t),:);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by