joining two matrices by column 1

2 views (last 30 days)
How can I combine two matrices, say:
a = [29 315; 41 64; 42 130]
b = [29 260; 39 171; 41 430]
I need the following:
c = [29 315 260; 39 0 171; 41 64 430; 42 130 0]
Combine the first column from a and b to form the first column in c (no repeated values). Then add the corresponding second columns from a and b to the second and third in c (zero if no match).
I need to do this for a large dataset. I have no idea how to proceed.
  1 Comment
Bob Thompson
Bob Thompson on 28 Sep 2018
I would suggest initializing an array of 0s first, just to make sure you don't have any uneven indices. I don't entirely know how to write the rest of it, but my guess would be some kind of loop, a few if statements, and using the isunique() logic to reduce any duplicate inputs.

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 28 Sep 2018
A simplistic approach assuming 1st column numbers are sorted and do not repeat within each a and b variable:
c = unique([a(:,1);b(:,1)]);
c(ismember(c(:,1),b(:,1)),3) = b(:,2);
c(ismember(c(:,1),a(:,1)),2) = a(:,2);
If the simplistic assumptions above are not correct, then you would have to add code for sorting etc.
  1 Comment
Milan Lstiburek
Milan Lstiburek on 29 Sep 2018
This solves it. I very appreciate your help on this.

Sign in to comment.

More Answers (0)


Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by