필터 지우기
필터 지우기

using find on each column of a matrix independently

조회 수: 60 (최근 30일)
Noah Chrein
Noah Chrein 2015년 7월 13일
답변: Matt J 2015년 7월 14일
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