Info

此问题已关闭。 请重新打开它进行编辑或回答。

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

1 次查看(过去 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]
I hope someone could help me with this.

采纳的回答

Andrei Bobrov
Andrei Bobrov 2013-6-11
编辑:Andrei Bobrov 2013-6-11
EDIT
[ii,jj] = ismember(B(:,1:2),A(:,1:2),'rows');
C = B;
C(ii,3) = A(jj(ii),3);

更多回答(3 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-6-11
  2 个评论
Azzi Abdelmalek
Azzi Abdelmalek 2013-6-11
编辑:Azzi Abdelmalek 2013-6-11
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
Pourya Alinezhad 2013-6-11
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

Pourya Alinezhad
Pourya Alinezhad 2013-6-11
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

此问题已关闭。

标签

Community Treasure Hunt

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

Start Hunting!

Translated by