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?
조회 수: 2 (최근 30일)
이전 댓글 표시
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
답변 (3개)
Roger Stafford
2013년 6월 11일
[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
Roger Stafford
2013년 6월 11일
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
2013년 6월 11일
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
2013년 6월 11일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!