Index a row of a matrix using as indexes specific ordered elements
1 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
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).
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!