13

I have a column vector:

A = [1; 2; 3; 4; 4; 5; 5; 7]; 

I wish to exclude the elements of A that are in a second matrix B:

B = [4; 5]

The final result should be:

A = [1; 2; 3; 7]

I am pretty sure using MATLAB elegant syntaxing, this be accomplished without writing a for loop, but not sure how?

Eitan T
  • 32,660
  • 14
  • 72
  • 109
dr_rk
  • 4,395
  • 13
  • 48
  • 74
  • 1
    possible duplicate of [How do I remove elements at a set of indices in a vector in MATLAB?](http://stackoverflow.com/questions/3789847/) and [Retrieving the elements of a matrix with negated exact indexing with index matrix?](http://stackoverflow.com/questions/13918790/) – Eitan T May 29 '13 at 14:31
  • 2
    Note that `'` is the (complex conjugate) transpose function. So you should use a different letter for your second matrix. – Dennis Jaheruddin May 29 '13 at 14:32
  • 2
    Sorry, my bad. This is not a duplicate, I thought the second matrix holds indices to the rows to be removed, but it contains the elements themselves. – Eitan T May 29 '13 at 14:42

3 Answers3

20

I would use Afilt=A(~ismember(A,B));. This will return all elements of A which are not in B.

Marc Claesen
  • 16,778
  • 6
  • 27
  • 62
6

You can compare values with bsxfun:

A = A(all(bsxfun(@ne, A(:), B(:).'), 2))

This approach is especially good if you need to handle floating-point numbers (whereismember fails):

A(all(abs(bsxfun(@minus, A(:), B(:).')) >= eps, 2))

Instead of eps, you can set any tolerance threshold you want.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
2

EDIT: If you want to remove row 4 and 5 it is this, if you want to remove the rows with fours and fives check the other answers.

Simple as this

A = [1; 2; 3; 4; 4; 5; 5; 7];     
B = [4; 5];

A(B)=[];
Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122