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

1 Ansicht (letzte 30 Tage)
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.

Akzeptierte Antwort

Ahmet Cecen
Ahmet Cecen am 15 Mär. 2018
Bearbeitet: Ahmet Cecen am 15 Mär. 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).

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by