joining two matrices by column 1

2 Ansichten (letzte 30 Tage)
Milan Lstiburek
Milan Lstiburek am 28 Sep. 2018
Kommentiert: Milan Lstiburek am 29 Sep. 2018
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 Kommentar
Bob Thompson
Bob Thompson am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

James Tursa
James Tursa am 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 Kommentar
Milan Lstiburek
Milan Lstiburek am 29 Sep. 2018
This solves it. I very appreciate your help on this.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by