Removing like terms in a matrix

3 ビュー (過去 30 日間)
jesus escareno
jesus escareno 2017 年 8 月 31 日
回答済み: Jan 2017 年 9 月 1 日
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]

採用された回答

Akira Agata
Akira Agata 2017 年 9 月 1 日
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);

その他の回答 (2 件)

Jan
Jan 2017 年 9 月 1 日
There is a specific command for this job:
C = setdiff(A, B)

John BG
John BG 2017 年 8 月 31 日
編集済み: John BG 2017 年 8 月 31 日
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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by