FireSky
FireSky

Reputation: 181

Deleting rows if found in multiple arrays

I am having trouble with deleting a row that can be found in 2 of my arrays.

I have 2 arrays:

array1 = 1 2
         3 4
         5 6
         7 8
         9 10

array2 = 1 5
         7 8
         3 2

If the row appears in both arrays I want to delete it from array1 (example [7,8]). I tried this line of code below:

array1( find(array1(:,1) == array2(:,1)) ,:) = [];

but I am getting the following error message:

Error using == Matrix dimensions must agree.

What is the right way to do this?

Upvotes: 4

Views: 169

Answers (2)

chappjc
chappjc

Reputation: 30589

setdiff is more direct and allows you to preserve the original array if needed:

setdiff(array1,array2,'rows','stable')

Just for reference, you can also use interect:

[~,ia] = intersect(array1,array2,'rows');
array1(ia,:) = [];

However, I would use setdiff.

Upvotes: 1

bla
bla

Reputation: 26069

use ismember, for example, if your arrays are a and b:

a(ismember(a,b,'rows'),:)=[];

should do the job.

Upvotes: 5

Related Questions