using find on each column of a matrix independently
Afficher commentaires plus anciens
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 :)
Réponses (3)
Image Analyst
le 13 Juil 2015
0 votes
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 commentaire
Image Analyst
le 14 Juil 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.
Matt J
le 13 Juil 2015
map=bsxfun(@gt,M,thresh(:).');
[~, firstoverthresh]=max(map,[],1);
Matt J
le 14 Juil 2015
0 votes
There is also a MEX accelerated version on the FEX,
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!