Merge vector and matrix with duplicated common values

I have a large size of matrix and here is the sample. I have an another vector,B.
A =
1 1 2 3
1 2 3 5
1 3 4 2
2 4 5 5
2 5 1 6
2 6 4 3
3 7 5 1
3 7 3 2
3 8 2 1
4 9 5 4
4 9 6 1
4 0 2 5
...
B =
1
2
1
1
I would like to merge the vector and the matrix by matching first column of A and the vector B. Because there are multiple rows with the each value of first column (e.g., 4 rows for value 1, 3 rows of value 2 and so on), all of rows for each value should be merged for a new dataset (C as below), and duplicated value in vector B (as shown, 1 is duplicated), it seems to be challenging.
Here is what I want to have
C =
1 1 2 3
1 2 3 5
1 3 4 2
2 4 5 5
2 5 1 6
2 6 4 3
1 1 2 3
1 2 3 5
1 3 4 2
1 1 2 3
1 2 3 5
1 3 4 2

5 commentaires

@Boram Lim: please explain how C is derived from A and B. It is not clear from your question what their relationship is.
It is like stacking
Part of A, rows with 1 in the first column
1 1 2 3
1 2 3 5
1 3 4 2
Part of B, rows with 1 in the first column
2 4 5 5
2 5 1 6
2 6 4 3
Part of A, rows with 1 in the first column
1 1 2 3
1 2 3 5
1 3 4 2
Part of A, rows with 1 in the first column
1 1 2 3
1 2 3 5
1 3 4 2
Because vector B has (1 ,2 1, 1), I want to have C by stacking rows with each of B values in the first column of A. I can do it by using innerjoin(B,A,'Key','name of common variable'). However, how to do it without using innerjoin?
Stephen23
Stephen23 le 6 Mai 2018
Modifié(e) : Stephen23 le 6 Mai 2018
@Boram Lim: then the C in your question is different to the one in your comment above (see "part B"). Which is correct?
Oh, I made a mistake. you are right. I just updated. Thank you

Connectez-vous pour commenter.

 Réponse acceptée

Stephen23
Stephen23 le 6 Mai 2018
Modifié(e) : Stephen23 le 6 Mai 2018
One solution using accumarray:
>> A = [1,1,2,3;1,2,3,5;1,3,4,2;2,4,5,5;2,5,1,6;2,6,4,3;3,7,5,1;3,7,3,2;3,8,2,1;4,9,5,4;4,9,6,1;4,0,2,5];
>> B = [1;2;1;1];
>> R = 1:size(A,1);
>> Z = accumarray(A(:,1),R.',[],@(r){A(r,:)});
>> C = vertcat(Z{B})
C =
1 1 2 3
1 2 3 5
1 3 4 2
2 4 5 5
2 5 1 6
2 6 4 3
1 1 2 3
1 2 3 5
1 3 4 2
1 1 2 3
1 2 3 5
1 3 4 2

Plus de réponses (0)

Catégories

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by