Removing like terms in a matrix

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by