Skip to content

Instantly share code, notes, and snippets.

@ChrisRackauckas
Last active August 18, 2016 21:44
Show Gist options
  • Save ChrisRackauckas/92bb8d13cc1fdac13f0a4e56fd931a68 to your computer and use it in GitHub Desktop.
Save ChrisRackauckas/92bb8d13cc1fdac13f0a4e56fd931a68 to your computer and use it in GitHub Desktop.
type Points{T<:Number} # Note you can make this immutable and still change the contents of the vectors
x::Vector{T}
y::Vector{T}
a::Vector{T}
end
type Point{T<:Number} # Let your points be any number, but match
x::T
y::T
a::T
end
#You can define an array interface for it
import Base: length, size, endof, getindex
Base.length(ps::Points) = length(ps.x) ## Assume all are the same size. You can check and throw an error
Base.size(ps::Points) = (length(ps.x),3)
Base.endof(ps::Points) = length(ps)
getindex(ps::Points,i::Int) = Point(ps.x[i],ps.y[i],ps.a[i])
function push!(ps::Points,p::Point)
push!(ps.x,p.x)
push!(ps.y,p.y)
push!(ps.a,p.a)
end
# Now the array interface works
# ps[i] returns Point(x[i],y[i],a[i])
# You can push! points into ps to make it bigger
n = 10000000
x = rand(n)
y = rand(n)
a = zeros(n)
ps = Points(x,y,a)
# Now the fast algorithm is written like this:
@time for i in eachindex(ps)
ps.a[i] = ps.x[i] * ps.y[i]
end
function update_a(ps::Points) #You can make a function which does the super fast version with threading
@Base.threads for i in eachindex(ps)
ps.a[i] = ps.x[i] * ps.y[i]
end
end
#But users will see ps[i] = Point(x,y,a), so it can still be easy to use/plot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment