How to add a matrix A to another matrix B with a different size and it should maintain rows of B which do not have the first two elements equal to the first two elements of a row in matrix A?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I got the following problem. if I have the following two matrices:
A=[1 2 1
3 4 1
7 8 1]
B=[1 2 0
2 6 0
3 4 0
4 9 0
5 2 0
6 1 0
7 8 0]
I need to add matrix A to matrix B with remaining the rows of matrix B. Only when the first two elements are the same, the row should be replaced. I need a matrix:
C=[1 2 1
2 6 0
3 4 1
4 9 0
5 2 0
6 1 0
7 8 1]
It has to work for a 41120x3 matrix.
1 Kommentar
Antworten (3)
Roger Stafford
am 11 Jun. 2013
[tf,loc] = ismember(B(:,1:2),A(:,1:2),'rows');
t = loc(tf);
C = B;
C(t,:) = A(t,:);
Note that if B contains more than one row with the same first two elements, this will select the one with the higher index.
5 Kommentare
Roger Stafford
am 11 Jun. 2013
A thousand pardons! My own code is in error. I should have written this:
[tf,loc] = ismember(B(:,1:2),A(:,1:2),'rows');
C = B;
C(tf,3:end) = A(loc(tf),3:end);
Roger Stafford
am 11 Jun. 2013
If I understand you correctly, the reason you are getting a 41120 x 5 array is that your system is NOT handling commas as you expect! It is interpreting them is dividing symbols between separate elements of a five-element row. Try this simple experiment on your machine:
x = [1,2 3,4]
and see how many elements x has and what they are. If there are two and they are fractional, your system is dealing with commas properly. If there are four and they are all integers, it is not using commas properly.
Azzi Abdelmalek
am 11 Jun. 2013
for k=1:size(B,1)
ii=find(ismember(A(:,1:2),B(k,1:2),'rows'),1);
if ~isempty(ii)
B(k,:)=A(ii,:);
end
end
Siehe auch
Kategorien
Mehr zu Numeric Types 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!