Combine rows of 2 Matrices based on a columns cell value

1 次查看(过去 30 天)
I have two matrices. The first matrix "A" has 2 columns and 425 rows of data. Matrix "B" has 10 columns and 468 rows of data.
I need to assign rows 5 through 9 of Matrix B into rows 3 through 7 of Matrix A based on matching values in column 2 of B and column 10 in A (2 and 10 are indexes). For example:
Matrix A:
711875 1
711883 32
711884 22
712548 43
Matrix B:
1950 11 22 5 -1.5 46 -1.9 21 1 1
1951 3 11 5 -2.0 42 -1.6 33 1 2
1958 2 12 8 -2.0 34 -2.6 16 1 3
1960 2 29 17 -1.9 41 -2.2 25 1 4
1962 1 7 6 -1.6 34 -1.7 18 1 5
1962 12 8 6 -2.1 34 -2.1 16 1 6
1963 12 14 8 -1.6 37 -1.8 17 2 7
1965 3 3 6 -1.6 43 -1.5 31 2 8
1966 1 24 8 -1.6 35 -2.1 16 3 9
1967 2 21 5 -1.5 41 -2.1 22 3 10
The output should then be:
[711875, 1, 1950, 11, 22, 5, -1.5, 46, -1.9, 21, 1, 1]
where the " , " denotes columns. Therefore the first two columns would be from Matrix A while the last 10 columns would be from Matrix B. So 12 columns in total.

采纳的回答

per isakson
per isakson 2016-9-28
编辑:per isakson 2016-9-29
Try the code below. (Note that I have modified the example somewhat. All values of A(:,2) should be members of B(:,10) ???)
A = [
711875 1
711883 4
711884 7
712548 10 ];
B = [
1950 11 22 5 -1.5 46 -1.9 21 1 1
1951 3 11 5 -2.0 42 -1.6 33 1 2
1958 2 12 8 -2.0 34 -2.6 16 1 3
1960 2 29 17 -1.9 41 -2.2 25 1 4
1962 1 7 6 -1.6 34 -1.7 18 1 5
1962 12 8 6 -2.1 34 -2.1 16 1 6
1963 12 14 8 -1.6 37 -1.8 17 2 7
1965 3 3 6 -1.6 43 -1.5 31 2 8
1966 1 24 8 -1.6 35 -2.1 16 3 9
1967 2 21 5 -1.5 41 -2.1 22 3 10 ];
C = cat( 2, A, B( A(:,2), : ) );
[~,ixb] = ismember( A(:,2), B(:,10) );
D = cat( 2, A, B( ixb, : ) );
all( C(:)==D(:) )
If neither C nor D is what you want, please review your question.

更多回答(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