Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

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

1 vue (au cours des 30 derniers jours)
Glenn Roumen
Glenn Roumen le 11 Juin 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.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 11 Juin 2013
Modifié(e) : Andrei Bobrov le 11 Juin 2013
EDIT
[ii,jj] = ismember(B(:,1:2),A(:,1:2),'rows');
C = B;
C(ii,3) = A(jj(ii),3);
  3 commentaires
Andrei Bobrov
Andrei Bobrov le 11 Juin 2013
EDIT
Glenn Roumen
Glenn Roumen le 11 Juin 2013
Thank you very much!

Plus de réponses (3)

Azzi Abdelmalek
Azzi Abdelmalek le 11 Juin 2013
  2 commentaires
Glenn Roumen
Glenn Roumen le 11 Juin 2013
I editted the question because I need something else.
Azzi Abdelmalek
Azzi Abdelmalek le 11 Juin 2013
Modifié(e) : Azzi Abdelmalek le 11 Juin 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
Pourya Alinezhad le 11 Juin 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
  1 commentaire
Glenn Roumen
Glenn Roumen le 11 Juin 2013
I editted the question because I need something else.

Pourya Alinezhad
Pourya Alinezhad le 11 Juin 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
  1 commentaire
Pourya Alinezhad
Pourya Alinezhad le 11 Juin 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

Cette question est clôturée.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by