fastest way to find the first non-zero value in an array [message #59680] |
Tue, 08 April 2008 01:04  |
smasson
Messages: 1 Registered: April 2008
|
Junior Member |
|
|
Hi,
I want to find the first non-zero value of an array. Is there a faster
way to do this than with the "where" command: (where(array ne 0))[0]
"Where" will look for all non-zero values and I only need the first
one. It would be great if I could stop "where" in its search process
as soon as it found one element...
sebastien
|
|
|
Re: fastest way to find the first non-zero value in an array [message #59764 is a reply to message #59680] |
Tue, 08 April 2008 11:41  |
Rick Towler
Messages: 821 Registered: August 1998
|
Senior Member |
|
|
smasson@ wrote:
> I want to find the first non-zero value of an array. Is there a faster
> way to do this than with the "where" command: (where(array ne 0))[0]
> "Where" will look for all non-zero values and I only need the first
> one. It would be great if I could stop "where" in its search process
> as soon as it found one element...
I agree. You should submit a feature request so you can pass a keyword
specifying FIRST or LAST and optionally the number of first or last
elements you want returned. Something like:
idx = WHERE(array ne 0, /FIRST)
Returns a scalar containing the index of the first non-zero element of
array.
idx = WHERE(array ne 0, FIRST=10)
Returns a 10 element vector containing the first 10 indices where array
is not equal to 0.
LAST would function in the same way except it would start from the end
of the array and work backwards.
COMPLIMENT, and NCOMPLIMENT would function as they do now but of course
COMPLIMENT would return indices for all elements in "array" beyond the
point WHERE short-circuited.
-Rick
|
|
|
Re: fastest way to find the first non-zero value in an array [message #59770 is a reply to message #59680] |
Tue, 08 April 2008 07:23  |
Foldy Lajos
Messages: 268 Registered: October 2001
|
Senior Member |
|
|
On Tue, 8 Apr 2008, smasson@locean-ipsl.upmc.fr wrote:
> Hi,
>
> I want to find the first non-zero value of an array. Is there a faster
> way to do this than with the "where" command: (where(array ne 0))[0]
> "Where" will look for all non-zero values and I only need the first
> one. It would be great if I could stop "where" in its search process
> as soon as it found one element...
>
> sebastien
>
(where(array))[0] will be a little bit faster, because it spares a temp
array creation and write.
regards,
lajos
|
|
|