Why not something like this?
function piecewise(x::Float64, breakpts::Vector{Float64}, f::Vector{Function}) @assert(issorted(breakpts)) @assert(length(breakpts) == length(f)+1) b = searchsortedfirst(breakpts, x) return f[b](x) end piecewise(X::Vector{Float64}, bpts, f) = [ piecewise(x,bpts,f) for x in X ]
Here you have a list of (sorted) breakpoints, and you can use optimized searchsortedfirst to find the first breakpoint b greater than x . The edge case, when the breakpoint is greater than x , is also handled accordingly, since length(breakpts)+1 returned, so b is the correct index into the function vector f .
Alex williams
source share