Skip to content

Instantly share code, notes, and snippets.

@milktrader
Created March 21, 2013 14:19
Show Gist options
  • Save milktrader/5213361 to your computer and use it in GitHub Desktop.
Save milktrader/5213361 to your computer and use it in GitHub Desktop.
sum array with NaN with two approaches. Create a new array or pass through a do loop in Julia
foo = [ones(1000), NaN]
function removeNaN_sum(x::Array)
newa = typeof(x[1])[]
for i in 1:length(x)
if x[i] <= max(x)
push!(newa, x[i])
end
end
sum(newa)
end
function doremoveNaN_sum(x::Array)
sum(x) do x
isnan(x) ? 0 : x
end
end
julia> removeNaN_sum(foo)
1000.0
julia> doremoveNaN_sum(foo)
1000.0
julia> timetrial(removeNaN_sum, foo, 100)
0.01151830281
julia> timetrial(doremoveNaN_sum, foo, 100)
0.00011032616
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment