Merging two dissimilar matrix based on common row element
조회 수: 1 (최근 30일)
이전 댓글 표시
I have two arrays
A = 1 2.576
1 2.822
13 2.679
13 2.786
25 2.653
25 2.596
25 2.565
B= 1 nan
1 nan
1 nan
2 nan
2 nan
2 nan
.. nan
.. nan
13 nan
13 nan
13 nan
14 nan
14 nan
14 nan
.. nan
.. nan
20 nan
20 nan
20 nan
.. nan
.. nan
.. nan
25 nan
25 nan
25 nan
I have to create a third matrix C, which have all variables combined based on first column of B, while putting the values of A into it. The empty element, for which no values of A is available should be filled with nan. Desired output is matrix C.
C = 1 2.576
1 2.822
1 nan
2 nan
2 nan
2 nan
3 nan
3 nan
3 nan
4 nan
4 nan
4 nan
.. nan
.. nan
10 nan
10 nan
10 nan
13 2.679
13 2.786
14 nan
14 nan
14 nan
.. nan
.. nan
20 nan
20 nan
20 nan
25 2.653
25 2.596
25 2.565
I tried with intersect, however, it's not working for this case since the common column contains repeated values. Any help?
댓글 수: 0
답변 (2개)
Andrei Bobrov
2017년 8월 4일
편집: Andrei Bobrov
2017년 8월 4일
A = [1 2.576
1 2.822
13 2.679
13 2.786
25 2.653
25 2.596
25 2.565];
B = [kron((1:25)',[1;1;1]),nan(25*3,1)];
C = B;
p = findgroups(A(:,1));
AA = [A(:,1),cell2mat(accumarray(p,1,[],@(x){(1:numel(x))'}))];
q = findgroups(B(:,1));
BB = [B(:,1), cell2mat(accumarray(q,1,[],@(x){(1:numel(x))'}))];
C(ismember(BB,AA,'rows'),2) = A(:,2);
댓글 수: 2
Jan
2017년 8월 5일
Or with simple loops:
C = B;
kC = 1;
nC = size(C, 1);
for iA = 1:size(A, 1)
a = A(iA, 1);
for iC = kC:nC
if C(iC, 1) == a
C(iC, 2) = A(iA, 2);
kC = iC + 1;
break; % Stop for iC loop
end
end
end
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!