How can I merge two different tables using the first column in common?

1 view (last 30 days)
A(class double)
[1 7;
3 15]
B(class double)
[2 9;
5 10]
C = (A+B)
[1 7 0;
2 9 0;
3 15 0;
4 0 0;
5 0 10]
  3 Comments
the cyclist
the cyclist on 26 Mar 2015
Edited: the cyclist on 26 Mar 2015
The rule seems to be
  1. merge and sort on the first column of both arrays
  2. put corresponding values from A into 2nd column of C
  3. put corresponding values from B into 3rd column of C
I think that the second row of C is supposed to be
[2 0 9]

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 26 Mar 2015
A = [1 7;
3 15]
B = [2 9;
5 10]
Ca = [A, zeros(size(A,1),1)];
Cb = [B(:,1), zeros(size(B,1),1), B(:,2)];
M1 = union(A(:,1),B(:,1));
M2 = setdiff((1:max(M1))',M1);
M3 = [M2, zeros(size(M2,1),2)];
C = sortrows([Ca; Cb; M3],[1]);
  3 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!