Reputation: 47
I have two values (k and j) which I know are within an nx3 matrix (M). I know that they're and on the same row and that j is always to the right of k, so if k is in M(2,1), then j will be in M(2,2). I tested for this earlier in the function, but now I want to know which row that is for a given k and j. I need the row number of their location to proceed. There are no duplicate combinations of k and j in the matrix.
So if I have the matrix
M=
1 4 5
1 5 7
k j 5
4 5 6
2 3 1
Then I want to know that they're in row 3. None of the columns are ordered.
What I have tried:
I used the code below
[row,~] = find(M==k);
I'm not sure how to look for a combination of them. I want to avoid using the find function. I hope to potentially use logical indexing.
How do I go about doing this? I hope this question makes sense.
Upvotes: 4
Views: 104
Reputation: 2619
Use this:
row = find(((M(:,1) == k ) & ( M(:,2) == j)) | ((M(:,1) == k ) & ( M(:,3) == j)) | ((M(:,2) == k ) & ( M(:,3) == j)) )
Also, logical indexing can only give you a matrix with zeros
at all other positions and one
at your required position. But to get the index of that position, you will have to use find
.
Upvotes: 1
Reputation: 2256
Slightly different version on bsxfun
. This one doesn't limit the matrix to three columns.
find(sum(((bsxfun(@eq,M,j) + bsxfun(@eq,M,k)) .* M).' ) == j+k >0)
Case 1:
M = [
1 4 5
1 5 7
6 7 1
4 5 6
2 3 1]
k=6;j=7;
ans = 3
Case 2:
M=[
1 4 5
1 5 7
1 6 7
4 5 6
2 3 1
];
k=6;j=7;
ans = 3
Upvotes: 1
Reputation: 221554
You can use bsxfun
-
find(all(bsxfun(@eq,A(:,1:2),[k,j]),2) | all(bsxfun(@eq,A(:,2:3),[k,j]),2))
Being a relational operation with bsxfun
, according to this post on benchmarked results
, this should be pretty efficient.
Sample runs
Case #1 :
A =
1 4 5
1 5 7
6 7 1
4 5 6
2 3 1
k =
6
j =
7
>> find(all(bsxfun(@eq,A(:,1:2),[k,j]),2) | all(bsxfun(@eq,A(:,2:3),[k,j]),2))
ans =
3
Case #2 :
A =
1 4 5
1 5 7
1 6 7
4 5 6
2 3 1
k =
6
j =
7
>> find(all(bsxfun(@eq,A(:,1:2),[k,j]),2) | all(bsxfun(@eq,A(:,2:3),[k,j]),2))
ans =
3
Upvotes: 1