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!