count non-zero array elements

is there a short cut or easy way to count the number of non-zero elements in an array of doubles?


No, you’d have to cycle through them and count.

dim cnt as integer
for each d as double in doublesArr
  if d <> 0.0 then cnt = cnt + 1
next d

Should be pretty fast.

Yeah, I knew to do that, I was just hoping there was a one line function that would return the number of positive elements…

The Xojo language is extensible in some ways, so you could write your own using the Extends keyword:

function CountPositives extends dArray() as double as integer
  dim cnt as integer
  for each d as double in dArray
    if d >0 then cnt=cnt+1
   return cnt
end function

You can then use the function in your code using dot notation

  dim d() as double
  dim n as integer
  n = d.CountPositives

This code might be faster:

  dim cnt as integer
  dim thisIndex as integer = doublesArr.IndexOf( 0. )
  while thisIndex <> -1
    cnt = cnt + 1
    if thisIndex = doublesArr.Ubound then
      thisIndex = doublesArr.IndexOf( 0., thisIndex + 1 )
    end if
  cnt = doublesArr.Ubound - cnt + 1