Horizontally join two datasets of different sizes based on a common field

4 vues (au cours des 30 derniers jours)
Lucy
Lucy le 8 Oct 2014
Commenté : Lucy le 9 Oct 2014
Dear all,
I have two matrices (A and B) that I want to join together horizontally based on a common field to create an output as shown in C. I have included a small example of my very large datasets:
A=
3304 1 329 0
3304 1 819 0
3304 2 76 0
3304 1 12 0
3304 2 971 1
3304 1 76 2
3304 2 230 2
3304 1 258 2
3304 1 27 3
3304 1 73 3
3304 2 179 3
3304 3 190 3
B=
0 29.7 27.7 13.2
1 26.3 24.3 14.1
2 28.1 26.1 24.5
3 27.1 25.1 13.1
C=
3304 1 329 0 0 29.7 27.7 13.2
3304 1 819 0 0 29.7 27.7 13.2
3304 2 76 0 0 29.7 27.7 13.2
3304 1 12 0 0 29.7 27.7 13.2
3304 2 971 1 1 26.3 24.3 14.1
3304 1 76 2 2 28.1 26.1 24.5
3304 2 230 2 2 28.1 26.1 24.5
3304 1 258 2 2 28.1 26.1 24.5
3304 1 27 3 3 27.1 25.1 13.1
3304 1 73 3 3 27.1 25.1 13.1
3304 2 179 3 3 27.1 25.1 13.1
3304 3 190 3 3 27.1 25.1 13.1
I have spent many hours on this what I imagine is a very simple task, so any help would be appreciated.

Réponse acceptée

Thorsten
Thorsten le 8 Oct 2014
Modifié(e) : Thorsten le 8 Oct 2014
C = [A B(A(:,4)+1, :)];
  3 commentaires
Guillaume
Guillaume le 8 Oct 2014
This answer assumes that the first column of B is always 0,1,2,3,4,etc. in that order, with no gap. A more generic solution, which works regardless of the ordering and values of B's first column:
[tf, ib] = ismember(A(:, 4), B(:, 1));
C = [A(tf, :) B(ib, :)];
The above also works if the common field is not found in B (it just does not include that row).
Lucy
Lucy le 9 Oct 2014
Great, this will be very useful. Much appreciated

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by