find() along a given dimension of a matrix
56 次查看(过去 30 天)
显示 更早的评论
I have an n-by-m matrix, A. I would like to find the last element in each row of A satisfying some condition. Intuitively, I'm looking for a way to use the find() command along a given dimension of A like the following syntax:
k = find(X,n,direction,dimension)
where the syntax is the same as the current find() command, except there is an additional argument that tells MATLAB to perform the search along a specific dimension of the array X. And I would use it like
k = find(A < 5, 1, 'last', 2);
This would say, return the column index (dimension 2) of the last 1 element of each row of A satisfying the condition A < 5. I would expect k to be a column vector of length size(A,1) with the i-th element of k giving the desired column index.
Right now, I'm just using find() on each row inside of a for-loop:
for i = 1:size(A,1)
k(i) = find(A(i,:) < 5, 1, 'last');
end
but I'm trying to figure out a way to do this without a for-loop. For a small matrix the for loop wouldn't be a problem, but my matrix, A, has millions of rows, so the for-loop has millions of iterations and is pretty slow. Any suggestions?
1 个评论
jgg
2016-1-25
This will work, but I think it's slower than looping.
table2array(rowfun(@(A)(find(A > 2,1,'last')),table(A)))
回答(3 个)
Matt J
2016-1-25
编辑:Matt J
2016-1-25
The following finds the final value in each row, but you can easily adapt it to other dimensions/directions.
function k = rowwiseLast(A)
%Finds locations k(i) of final non-zero value in each row A(i,:), with k(i)=NaN if
%the entire row is zero.
m=size(A,2);
[val,loc] = max( fliplr(logical(A)), [],2);
k=m+1-loc;
k(val==0)=nan;
end
If there is no value satisfying the criterion, than k(i)=nan for that row.
2 个评论
Matt J
2016-1-27
编辑:Matt J
2016-1-27
My solution will only find at most one occurrence in each row. The FEX submission truly is enabled with all the functionality of the FIND command, and can find n>1 occurrences if desired. Also, to implement direction='last', I need to apply the flip() command, which creates a theoretically unnecessary extra copy of the input array. This can be avoided by using a MEX file, as the FEX version appears to do.
Image Analyst
2016-1-25
The for loop is fine. I mean, it's not like you have tens of millions of columns or anything do you?
2 个评论
Image Analyst
2016-1-25
Sorry, I meant rows since you're iterating over rows. Still might not be a problem even for millions of rows. How long is it taking? I just did 10 million iterations and it took 0.03 seconds, though I didn't have a find() in there.
Did you time jgg's suggestion?
另请参阅
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!