Define piecewise functions in Julia

I have an application in which I need to define a piecewise function IE, f (x) = g (x) for [x in some range], f (x) = h (x) for [x in some other range] ,. .. etc.

Is there a good way to do this in Julia? I would prefer not to use if-else, because it seems that I will need to check each range for large x values. What I thought was to build an array of functions and an array of borders / ranges, then when f (x) is called, do a binary search in the ranges to find the corresponding index and use the corresponding function (IE, h (x) , g (x), etc.

It seems that such a mathematically friendly language may have some functionality for this, but the documentation does not mention piecewise this way. Hope someone else thought, thanks!

+8
julia-lang piecewise
source share
3 answers

with the Heaviside function you can perform the interval function:

function heaviside(t) 0.5 * (sign(t) + 1) end 

and

 function interval(t, a, b) heaviside(ta) - heaviside(tb) end function piecewise(t) sinc(t) .* interval(t,-3,3) + cos(t) .* interval(t, 4,7) end 

and I think that he could also implement the subtype interval, he would be much more elegant

+1
source share

I tried to implement the piecewise function for Julia , and this is the result:

 function piecewise(x::Symbol,c::Expr,f::Expr) n=length(f.args) @assert n==length(c.args) @assert c.head==:vect @assert f.head==:vect vf=Vector{Function}(n) for i in 1:n vf[i]=@eval $x->$(f.args[i]) end return @eval ($x)->($(vf)[findfirst($c)])($x) end pf=piecewise(:x,:([x>0, x==0, x<0]),:([2*x,-1,-x])) pf(1) # => 2 pf(-2) # => 2 pf(0) # => -1 
+1
source share

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 .

+1
source share

All Articles