SMH
SMH

Reputation: 1316

Intersect between two vectors but should have the same index

I am trying to get the intersection between two vectors but the index in both vectors should be the same. For example: x = [1 2 3 4 5 6 7 80 9 100 11 12 103 14 150 16 170 18 20 19] y = [22 1 3 40 5 4 70 8 90 10 110 12 13 140 15 160 17 18 19 20] the intesection should be [3 5 12 18] only.

My code:

x = [1  2 3  4  5 6 7  80 9  100 11  12 103 14  150 16  170 18 20 19];
y = [22 1 3  40 5 4 70 8  90 10  110 12 13  140 15  160 17  18 19 20];
inter = intersect(x,y);

Upvotes: 2

Views: 119

Answers (1)

David
David

Reputation: 8459

It's simple with logical indexing:

>> x = [1  2 3  4  5 6 7  80 9  100 11  12 103 14  150 16  170 18 20 19];
>> y = [22 1 3  40 5 4 70 8  90 10  110 12 13  140 15  160 17  18 19 20];
>> x(x==y)
ans =
     3     5    12    18
>> x(abs(x-y)<=3) %// or y(abs(x-y)<=3) for the y values instead of the x values
ans =
     2     3     5     6    12    18    20    19

Upvotes: 4

Related Questions