Merge matrices by matching first column values in MATLAB?
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Natalie Williams
el 6 de Jul. de 2016
Comentada: Robert
el 6 de Jul. de 2016
I have two matrices A and B, where they share some common values in the first column. I would like to merge these into one matrix giving only the values they have in common in the first column along with their respective values in the other columns. For example
A= 4 5.3
5 7.3
8 2.5
9 4.7
B= 1 3.6 0.4
2 3.9 0.6
3 9.2 0.9
4 5.1 0.1
5 0.7 0.5
6 8.3 0.7
7 7.3 0.2
8 1.6 0.6
9 4.6 0.2
The output would be
C= 4 5.3 5.1 0.1
5 7.3 0.7 0.5
8 2.5 1.6 0.6
9 4.7 4.6 0.2
My actual data sets are much longer but this is the general idea.
Thanks
0 comentarios
Respuesta aceptada
Robert
el 6 de Jul. de 2016
A= [4 5.3
5 7.3
8 2.5
9 4.7];
B= [1 3.6 0.4
2 3.9 0.6
3 9.2 0.9
4 5.1 0.1
5 0.7 0.5
6 8.3 0.7
7 7.3 0.2
8 1.6 0.6
9 4.6 0.2];
[~,ia,ib] = intersect(A(:,1),B(:,1));
C = [A(ia,1:2),B(ib,2:3)]
1 comentario
Robert
el 6 de Jul. de 2016
The difference between this answer and Azzi's is that this works even if not all values of the first column in A appear in the first column of B. Delete the last row of B to see the difference.
Más respuestas (1)
Azzi Abdelmalek
el 6 de Jul. de 2016
A= [4 5.3
5 7.3
8 2.5
9 4.7]
B= [1 3.6 0.4
2 3.9 0.6
3 9.2 0.9
4 5.1 0.1
5 0.7 0.5
6 8.3 0.7
7 7.3 0.2
8 1.6 0.6
9 4.6 0.2]
B1=B(ismember(B(:,1),A(:,1)),:)
C=[A B1(:,2:3)]
0 comentarios
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!