joining two matrices by column 1

조회 수: 2 (최근 30일)
Milan Lstiburek
Milan Lstiburek 2018년 9월 28일
댓글: Milan Lstiburek 2018년 9월 29일
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
Bob Thompson
Bob Thompson 2018년 9월 28일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2018년 9월 28일
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
Milan Lstiburek
Milan Lstiburek 2018년 9월 29일
This solves it. I very appreciate your help on this.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by