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

2 ビュー (過去 30 日間)
Nikolas Theodoropoulos
Nikolas Theodoropoulos 2018 年 3 月 15 日
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
Ahmet Cecen 2018 年 3 月 15 日
編集済み: Ahmet Cecen 2018 年 3 月 15 日
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 件のコメント
Nikolas Theodoropoulos
Nikolas Theodoropoulos 2018 年 3 月 16 日
Yes, that's quite close to what I am looking for, thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by