Path: news.mathworks.com!newsfeed-00.mathworks.com!newsfeed2.dallas1.level3.net!news.level3.com!postnews.google.com!news1.google.com!npeer01.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!llnews!53ab2750!not-for-mail
From: Peter Boettcher <boettcher@ll.mit.edu>
Newsgroups: comp.soft-sys.matlab
Subject: Re: N-dimensional find
References: <gnhibi$s1m$1@fred.mathworks.com>
Message-ID: <muyocwzpn3h.fsf@G99-Boettcher.llan.ll.mit.edu>
Organization: MIT Lincoln Laboratory
User-Agent: Gnus/5.110006 (No Gnus v0.6) Emacs/23.0.0 (gnu/linux)
Cancel-Lock: sha1:9psfFB8WEvhkolMu33sQfmFBQv8=
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Lines: 42
Date: Wed, 18 Feb 2009 14:21:54 -0500
NNTP-Posting-Host: 155.34.163.93
X-Complaints-To: news@ll.mit.edu
X-Trace: llnews 1234984914 155.34.163.93 (Wed, 18 Feb 2009 14:21:54 EST)
NNTP-Posting-Date: Wed, 18 Feb 2009 14:21:54 EST
Xref: news.mathworks.com comp.soft-sys.matlab:519217


"Sven" <sven.holcombe@gmail.deleteme.com> writes:

> 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.


Not sure about faster, but you could abuse the behavior of max:

[dummy firstIdxs] = max(logical(BW));

That is, 1 is the max value, and the location of that max value is the
one you're looking for.  "help max" says that the first maximum is the
one that counts.

If this is faster, it's only because the loop overhead is bad.  The find
solution technically only has to look at the values up to the first 1 in
each column, where the max solution has to look at every single value in
the matrix.

-Peter