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!