Matlab:使用矢量化在固定的第一个和最后一个元素中搜索矩阵中的行

tim*_*tim 1 matlab matrix vectorization find

我有一个像下面这样的矩阵(任意cols/rows):

1    0    0    0    0
1    2    0    0    0
1    2    3    0    0
1    2    3    4    0
1    2    3    4    5
1    2    5    0    0
1    2    5    3    0
1    2    5    3    4
1    4    0    0    0
1    4    2    0    0
1    4    2    3    0
1    4    2    5    0
1    4    2    5    3
1    4    5    0    0
1    4    5    3    0
2    0    0    0    0
2    3    0    0    0
2    3    4    0    0
2    3    4    5    0
2    5    0    0    0
2    5    3    0    0
2    5    3    4    0
3    0    0    0    0
3    4    0    0    0
3    4    2    0    0
3    4    2    5    0
3    4    5    0    0
Run Code Online (Sandbox Code Playgroud)

现在我想得到第一个元素是某个值X的所有行,最后一个元素(即最后一个元素!= 0)是一个特定值Y,或者转过来:第一个是Y,最后一个是X .

看不到任何不使用for-loop的快速代码:(谢谢!

编辑:要使用某个第一个元素过滤所有行非常简单,您无需在此帮助我.因此,我们假设我只想执行以下操作:过滤最后一个元素(即每行中最后一个元素!= 0)的所有行是X或Y.

编辑非常 感谢您的帖子.我使用473408*10元素的矩阵对三种可能的解决方案进行了基准测试.这是基准标记:http: //pastebin.com/9hEAWw9a

结果是:

t1 = 2.9425 Jonas
t2 = 0.0999 Brendan
t3 = 0.0951 Oli
Run Code Online (Sandbox Code Playgroud)

非常感谢你们,我坚持使用Oli的解决方案,因此接受它.感谢所有其他解决方案!

Jon*_*nas 5

您需要做的就是找到每一行的最后一个非零元素的线性索引.其余的很简单:

[nRows,nCols] = size(A);
[u,v] = find(A); %# find all non-zero elements in A
%# for each row, find the highest column index with accumarray
%# and convert to linear index with sub2ind
lastIdx = sub2ind([nRows,nCols],(1:nRows)',accumarray(u,v,[nRows,1],@max,NaN));
Run Code Online (Sandbox Code Playgroud)

要过滤行,您可以编写

goodRows = A(:,1) == X & A(lastIdx) == Y
Run Code Online (Sandbox Code Playgroud)