Merging matrices by comparison of values of several columns

1 次查看(过去 30 天)
I have 2 matrices of different size. Matrix A is 1000x18, while B has 950x10 size. The values in columns 2,3 and 4 can be common for both data sets. My goal is to merge them into single matrix consisting of shared values from columns 2:4 and corresponding to them values from column 5 in A and columns 6 and 8 from B. I tried to use this code, but it fails in generating combined matrix C:
[j] = intersect(out1(:,2:4),out2(:,2:4),'rows');
C = [out2(j,5) out1(j,[6 8])];
I would appreciate any help.

采纳的回答

Guillaume
Guillaume 2019-10-4
Nearly right
[~, whichArows, whichBrows] = intersect(out1(:, 2:4), out2(:, 2:4), 'rows');
C = [out2(whichBrows, 5), out1(whichArows, [6 8])]; %you may also want to include columns 2 to 4
Note that if the keys (columns 2:4) are present more than once in either input you'll only get one of them in the output.
Another option is to convert your matrices to tables. Then you can perform an innerjoin, outerjoin or a plain join:
tout1 = array2table(out1);
tout2 = array2table(out2);
joined = innerjoin(tout1, tout2, 'Keys', 2:4, 'LeftVariables', 5, 'RightVariables', [6 8]);

更多回答(0 个)

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by