user5739619
user5739619

Reputation: 1838

How check if pair of values exist in 2d Matlab array?

Say I have

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

If I then have x=3, y=7, how can I check that (3,7) exists in array a but also ensure that if I check for the pair x=3, y=8 (3,8), then it returns false and NOT true?

EDIT: (3,7) should return true but (3,8) false because 3 and 7 are in the same column, but 3 and 8 are not. Also (7,3) should be false because for (x,y), xcorresponds to element in 1st row and y in 2nd row

EDIT2: I see isPresent = any(ismember(a.', [x y], 'rows')); for the arrray a.

But what if I have this: b=[1 5; 2 6; 3 7; 4 8]. Then how can I ensure that (3,7) is true but (7,3) is false?

Upvotes: 0

Views: 957

Answers (1)

beaker
beaker

Reputation: 16801

The easiest way is to use ismember, but it works on rows instead of columns, so we'll need to transpose the matrix first:

x = 3;
y = 7;
a=[1 2 3 4; 5 6 7 8];

isPresent = any(ismember(a.', [x y], 'rows'));

>> isPresent
isPresent = 1

Upvotes: 4

Related Questions