using find on each column of a matrix independently

73 views (last 30 days)
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 :)

Answers (3)

Image Analyst
Image Analyst on 13 Jul 2015
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 Comment
Image Analyst
Image Analyst on 14 Jul 2015
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.

Sign in to comment.


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

Matt J
Matt J on 14 Jul 2015

Products

Community Treasure Hunt

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

Start Hunting!