Graph Piecewise Function in Julia

How do graph a piecewise function?

The same way you plot any function:

using Plots

plot(1:50, sin)
f(x) = x<25 ? sin(x) : 0.5
plot(1:50, f)

The function f is defined piecewise:

2 Likes

great! where do I find this in the documentation? I want to do other things, like make x = 1/2 and otherwise x=2

@brett_knoss here is how I approach this problem:
Q: How do I graph a piecewise function?

Q1: how do I graph any function f in Julia?
Google “Julia Plots”. Find this: http://docs.juliaplots.org/latest/basics/
To plot any function f(x) over domain dom: plot(dom, f)
Example dom=1:50, f(x)=sin(x): plot(1:50, sin)

Q2: how do I create a piecewise function f in Julia?

function f(x)
    if x > 0 && x < 2 
        1
    elseif x >= 2 && x < 5
        2
    else
        7 
    end     
end

Then: plot(-10:10,f)

thanks! that is handy. I found out in the mahematic opreators docs, that there is an unequal symbol !=

so I was able to put

f(x)=x!=0 ? .5 : 2

g(x)=x!=0 2 : .5

h(x)= f(x) *g(x)

plot(1:50,f)
plot!(1:50,g)

and all worked, except I can’t see my plots for some reason, also I don’t know how to select colors, but that shouldn’t matter.

Works for me:

using Plots
f(x)=x!=0 ? .5 : 2
g(x)=x!=0 ? 2 : .5
h(x)= f(x)*g(x)
plot(1:50,f)
plot!(1:50,g)
plot!(1:50,h)

To answer your other question - you can set the linecolor attribute like so:

plot(1:50, f, linecolor = "mediumvioletred")
2 Likes