Merging two dissimilar matrix based on common row element
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Andrei Bobrov
am 4 Aug. 2017
Bearbeitet: Andrei Bobrov
am 4 Aug. 2017
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 Kommentare
Jan
am 5 Aug. 2017
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 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!