# How do I add a matrix to another matrix with different sizes?

1 view (last 30 days)
Glenn Roumen on 11 Jun 2013
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]
I hope someone could help me with this.

Andrei Bobrov on 11 Jun 2013
Edited: Andrei Bobrov on 11 Jun 2013
EDIT
[ii,jj] = ismember(B(:,1:2),A(:,1:2),'rows');
C = B;
C(ii,3) = A(jj(ii),3);
Glenn Roumen on 11 Jun 2013
Thank you very much!

Azzi Abdelmalek on 11 Jun 2013
B(A(:,1),:)=A
##### 2 CommentsShowHide 1 older comment
Azzi Abdelmalek on 11 Jun 2013
Glenn, if you need something else, you should post another question. Please post your initial question and add a question as a comment

Pourya Alinezhad on 11 Jun 2013
if you want to add matrix A to first raw's of B you can use the following code:
C=zeros(size(B));
C(1:size(A,1),:)=A;
C(size(A,1)+1:end,:)=B(size(A,1):end,:)
but as i can see in C matrix you mentioned every raw of A is in it's first index value raw.for example if we have [3 1 1] so the raw will appear in third raw and [7 1 1] will appear in seventh raw.for this purpose you can use below code:
C=B;
for i=1:size(A,1)
C(A(i,1),:)=A(i,:);
end
Glenn Roumen on 11 Jun 2013
I editted the question because I need something else.

Pourya Alinezhad on 11 Jun 2013
C=B;
for i=1:length(B)
for j=1:length(A)
if A(j,1:2)==B(i,1:2)
C(i,:)=A(j,:)
end
end
end
Pourya Alinezhad on 11 Jun 2013
and the result is as you want : C =
1 2 1
2 6 0
3 4 1
4 9 0
5 2 0
6 1 0
7 8 1

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!