# Index a row of a matrix using as indexes specific ordered elements

1 view (last 30 days)
Nikolas Theodoropoulos on 15 Mar 2018
I have stuck with a seemingly stupid thing but still to figure it out. I want to index the row of a matrix which has 2 elements in a specific order. For example, I want the row r of M matrix which has both 4 and 5 but in that order.
M = [1 5 6; 5 4 3; 9 4 5]
want = [5 4]
What I expect is r = 2 since [5 4] (with that order) are both there. Note: I don't want the third row. Even if both elements exist there, they are not in the desired order (i.e., 4 5 while I want 5 4). The farthest point I've reached so far is:
M = [1 5 6; 5 4 3; 9 4 5]
want(1,1,:) = [4 5];
indexToDesiredRows = all(any(bsxfun(@eq,M,want),2),3)
rowNumbers = find(indexToDesiredRows)
which unfortunately returns the third row as well.

Ahmet Cecen on 15 Mar 2018
Edited: Ahmet Cecen on 15 Mar 2018
This should work for most cases, it will also catch cases that wrap around though like a row [4 3 5]:
[row column] = find(((M == want(1)) + (circshift(M,[0,-1]) == want(2))) == 2);
If you don't want wrap around, you can ignore the output if column == size(M,2).
##### 1 CommentShowHide None
Nikolas Theodoropoulos on 16 Mar 2018
Yes, that's quite close to what I am looking for, thanks!