Micky Messer
Micky Messer

Reputation: 83

Check if two numbers are in the same row of a matrix

I have for example a matrix like this:

1    2    6
1    6    5
2    3    7
2    7    6
3    4    8
3    8    7
5    6   10
5   10    9
6    7   11
6   11   10
7    8   12
7   12   11

and I need a function that checks if two numbers are in the same row.

For example check(1,2) would be true, while check(1,3) would be false

I have defined the following function

function f = checkTri(i,j,D)
E=D';
p=any(E==i);
f=0;
for k=1:length(p)
if (p(k)==1)==1
    if((any(E(:,k)==j)==1))
        f=1;
    end
end
end

and it seems to work but maybe there is some more elegant way. Can somebody take a look at this please?

Upvotes: 1

Views: 649

Answers (2)

svdc
svdc

Reputation: 164

Assuming D is your matrix, iyour first element and j your second, you could do it as follows: (1) replace all elements that equal j by i and (2) use diff on each row and see if there is a 0 somewhere. You need to sort first because of how diff works. Code:

D(D==j) = i;
any(~all(diff(sort(matrix,2),1,2)))

will return 1 if i and j are in the same row and 0 otherwise. Suever's solution is more elegant though.

Upvotes: 0

Suever
Suever

Reputation: 65430

You can simply find the rows in the matrix that have a particular value using a combination of == and any. Then check all rows for both of your values.

M = [   1    2    6
        1    6    5
        2    3    7
        2    7    6
        3    4    8
        3    8    7
        5    6   10
        5   10    9
        6    7   11
        6   11   10
        7    8   12
        7   12   11];

% Check(1,2) - Sees is any row contains *both* 1 and 2
tf = any(any(M == 1, 2) & any(M == 2, 2));

% Check(1,3)
tf = any(any(M == 1, 2) & any(M == 3, 2));

% And if you want to find the matching row
row = find(any(M == 1, 2) & any(M == 2, 2));

Upvotes: 1

Related Questions