Removing like terms in a matrix

3 vues (au cours des 30 derniers jours)
jesus escareno
jesus escareno le 31 Août 2017
Réponse apportée : Jan le 1 Sep 2017
Let say i have to matrix A and B and wanted to produce a matrix C with the different terms of A and B.
A = [1 2 3 4 5 6 7 8 9]
B = [2 4 5 8 9]
so that
C = [1 3 6 7]

Réponse acceptée

Akira Agata
Akira Agata le 1 Sep 2017
ismember function can do this more easily, like:
A = [1 2 3 4 5 6 7 8 9];
B = [2 4 5 8 9];
idx = ismember(A,B);
C = A(~idx);

Plus de réponses (2)

Jan
Jan le 1 Sep 2017
There is a specific command for this job:
C = setdiff(A, B)

John BG
John BG le 31 Août 2017
Modifié(e) : John BG le 31 Août 2017
hi there
1.
the data
A = [1 2 3 4 5 6 7 8 9]
B = [2 4 5 8 9]
2.
with intersect. an if also comes useful because in this case length(A)>length(B) but it may be you have A B such length(B)>length(A)
if length(A)>=length(B)
[a,b,v]=find(A==intersect(A,B)');
elseif length(B)>length(A)
[b,a,v]=find(B==intersect(A,B)');
end
a =
1
2
3
4
5
b =
2
4
5
8
9
v =
5×1 logical array
1
1
1
1
1
3.
copy, just in case you don't want to change A and B
A2=A;B2=B;
4.
remove common elements
A2(b)=[];
B2(a)=[];
C=[A2 B2]
C =
1 3 6 7
if you find this answer useful would you please be so kind to consider marking my answer as Accepted Answer?
To any other reader, if you find this answer useful please consider clicking on the thumbs-up vote link
thanks in advance
John BG

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by