Path: news.mathworks.com!not-for-mail
From: <HIDDEN>
Newsgroups: comp.soft-sys.matlab
Subject: Re: N-dimensional find
Date: Wed, 18 Feb 2009 19:54:01 +0000 (UTC)
Organization: Erasmus MC
Lines: 34
Message-ID: <gnhp0p$1e8$1@fred.mathworks.com>
References: <gnhibi$s1m$1@fred.mathworks.com>
Reply-To: <HIDDEN>
NNTP-Posting-Host: webapp-02-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1234986841 1480 172.30.248.37 (18 Feb 2009 19:54:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Wed, 18 Feb 2009 19:54:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 870065
Xref: news.mathworks.com comp.soft-sys.matlab:519225


"Sven" <sven.holcombe@gmail.deleteme.com> wrote in message <gnhibi$s1m$1@fred.mathworks.com>...
> Hi there,
> 
> I've noticed myself running the following style of loop quite a bit when trying to find the 'first' pixel in an image along a dimension. This is somewhat like measuring from the top row of an image towards the bottom row of the image, and recording the first collision with an "on" pixel.
> 
> % BW is some binary image
> 
> firstIdxs = zeros(size(BW,2);
> for i=1:size(BW,2)
>   idx = find(BW(:,i),1,'first');
>   if ~isempty(idx)
>     firstIdxs(i) = idx;
>   end
> end
> 
> I see this as analogous to using, say, sum(BW, 2) to sum along the 2nd dimension, whereas I'm trying to do something like find(BW, dim).
> 
> Is there a faster solution? Or, perhaps more relevant: is there a solution that doesn't clutter up my .m files as much as this implementation? If not, I'll just have to function-ize this one.
> 
> Cheers,
> Sven.

Something like this?

bw = rand(10) > .8 ;

firstidx = zeros(1,size(bw,2)) ;
[R,C] = find(cumsum(cumsum(bw))==1) ;
firstidx(C) = R  % we need some care for all-zero columns

although I think the double cumsum makes it slower than a for-loop ;-)

hth
Jos