using find on each column of a matrix independently

60 次查看(过去 30 天)
Hello, I would like to use the find function on each row independently in a vectorized way.
for example, I want to find the first point that is above a threshold defined by which column I am in, let this be thresh(j) where j is the column.
let M be an m by n matrix, then for loop way of doing this is as follows:
firstoverthresh = zeros(1,n);
for j = 1:n
firstoverthresh(j) = find(M(:,j)>thresh(j),1);
end
this should return the n sized vector (since there are n columns) of values that I am trying to find.
Thank you :)

回答(3 个)

Image Analyst
Image Analyst 2015-7-13
There's nothing wrong with that way. It's fine: it works, it's intuitive, and it's fast. I don't know of any non-looping way that will be faster.
  1 个评论
Image Analyst
Image Analyst 2015-7-14
To compare Matt's solution and your "for loop" solution (with a constant threshold of 0.5:
n = 10000
M = rand(n,n);
tic
firstoverthresh = zeros(1,n);
for j = 1:n
firstoverthresh(j) = find(M(:,j)>.5,1);
end
toc
tic
map=bsxfun(@gt,M,0.5);
[~, firstoverthresh]=max(map,[],1);
toc
For a large matrix, a hundred million elements or 10,000 by 10,000, the for loop is faster.
Elapsed time is 0.125944 seconds.
Elapsed time is 0.151905 seconds.
while for a smaller array, like n = 100, Matt's bsxfun solution is faster.
Elapsed time is 0.000433 seconds.
Elapsed time is 0.000138 seconds.
though either one is so fast (less than a millisecond) you wouldn't notice the difference.

请先登录,再进行评论。


Matt J
Matt J 2015-7-13
map=bsxfun(@gt,M,thresh(:).');
[~, firstoverthresh]=max(map,[],1);

Matt J
Matt J 2015-7-14

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by