Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 nice way to do this in Julia? I'd rather not use if-else because it seems that I'd have to check every range for large values of x. The way that I was thinking was to construct an array of functions and an array of bounds/ranges, then when f(x) is called, do a binary search on the ranges to find the appropriate index and use the corresponding function (IE, h(x), g(x), etc.

It seems as though such a mathematically friendly language might have some functionality for this, but the documentation doesn't mention piecewise in this manner. Hopefully someone else has given this some thought, thanks!

like image 772
user3587051 Avatar asked Dec 27 '14 06:12

user3587051


1 Answers

with a Heaviside function you can do a interval function:

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

and

function interval(t, a, b)
   heaviside(t-a) - heaviside(t-b)
end

function piecewise(t)
   sinc(t) .* interval(t,-3,3) + cos(t) .* interval(t, 4,7)
end

and I think it could also implement a subtype Interval, it would be much more elegant

like image 87
elsuizo Avatar answered Oct 01 '22 22:10

elsuizo