Art
Art

Reputation: 462

Piecewise functions in Julia when the domain of the sub-function is different

Suppose I have a piecewise function foo(x) which is equal to x if x <= 0 and log(x) if x > 0. This function accepts a vector as an argument. So I tried the following:

function foo(x)
    (x .<= 0) .* x + (x .> 0) .* log(x)
end

Obviously this doesn't work when x < 0 as it tries to evaluate everything (even though it would be multiplied with 0. Any better way to do this?

Thanks!

Upvotes: 1

Views: 683

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

I think this is what you could try:

foo(x) = x > 0 ? log(x) : x

which assumes x is a scalar.

Then if v is a vector when you use it simply broadcast it like this foo.(v).

Upvotes: 2

Related Questions