Question

I'm working on MATLAB. I have the following matrices

A = [
    1 2 3 4
    5 6 7 8
    1 5 2 3
    6 7 8 9
    1 3 6 2
    6 3 1 6
    9 7 4 7
];

B = [
    1 5 2 3
    6 7 8 9
];

I want to find A-B so that the answer should be like,

ans = [
    1 2 3 4
    5 6 7 8
    1 3 6 2
    6 3 1 6
    9 7 4 7
];
Was it helpful?

Solution

Use setdiff with the 'rows' and 'stable' options:

>> C = setdiff(A,B,'rows','stable')
C =
     1     2     3     4
     5     6     7     8
     1     3     6     2
     6     3     1     6
     9     7     4     7

OTHER TIPS

Use ismember to find the common rows and neglect those in the final output.

Code

out = A(~ismember(A,B,'rows'),:)

Output

out =

     1     2     3     4
     5     6     7     8
     1     3     6     2
     6     3     1     6
     9     7     4     7
clear;
s=0;
A = [

    1 2 3 4
    5 6 7 8
    1 5 2 3
    6 7 8 9
    1 3 6 2
    6 3 1 6
    9 7 4 7
];

B = [

    1 5 2 3
    6 7 8 9
];

for i=1:size(B)

s=s+(ismember(A, B(i,:), 'rows'))

end

A_B = A(s==0,:)

@Divakar or @chappjc's answers are the way to go.

But I can't help inviting bsxfun to the party:

C = A(~any(squeeze(all(bsxfun(@eq, A.', permute(B, [2 3 1])))).'),:);

And its friend pdist2 is coming too:

C = A(all(pdist2(A, B, 'hamming').'),:);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top