Suppose I have two datasets:
A =
1991 1 23
1992 1 32
1993 1 25
1991 2 26
1992 2 68
1993 2 69
1994 2 67
and
B =
1991 1 99
1992 1 100
1991 2 88
1994 2 89
1995 2 87
Suppose the first column is year and the second column is firm id in each matrix. How could I merge the two matrices based on the two columns to get
C =
1991 1 23 99
1992 1 32 100
1993 1 25 NaN
1991 2 26 88
1992 2 68 NaN
1993 2 69 NaN
1994 2 67 89
1995 2 NaN 87

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 6월 24일
편집: Andrei Bobrov 2016년 6월 24일

0 개 추천

C = sortrows(unique([A(:,1:2);B(:,1:2)],'rows'),[2 1]);
C = [C,nan(size(C,1),2)];
C(ismember(C(:,1:2),A(:,1:2),'rows'),3) = A(:,3);
C(ismember(C(:,1:2),B(:,1:2),'rows'),4) = B(:,3);
or
AB = [A;B];
n = repelem([1;2],[size(A,1);size(B,1)]);
[a,~,c0] = unique(AB(:,1:2),'rows');
C = sortrows([a,accumarray([c0,n],AB(:,3),[],[],nan)],[2,1]);

댓글 수: 2

The first line giving me error as follows:
.
I replace with following line as it works..
C = [sortrows(unique([A(:,1:2);B(:,1:2)],'rows'),[2 1]),nan(size(unique([A(:,1:2);B(:,1:2)],'rows'),1),2)]
Andrei Bobrov
Andrei Bobrov 2016년 6월 24일
corrected

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 NaNs에 대해 자세히 알아보기

태그

질문:

2016년 6월 24일

댓글:

2016년 6월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by