Multivariable piecewise functions: Julia-basics help

Hi, I was wondering how to create a piecewise function of two variables

r(x,y) = \begin{cases} f(x,y) & d(x,y)\geq 0 \\ g(x,y) & d(x,y)<0\end{cases} and use it to plot the coordinate pair (x',y')= (m(x,y), n(x,y)) on xy- plane where both m and n are scalar [but also functions of r(x,y)].

So far I thought of creating x= -10:10 and y : -10:10 and to store their values in arrays and then just output array of m and n values. Is it the correct thought process? End goal is to plot (m,n) based on (x,y) based on different values of a. Sorry for the basic doubts. Any help is appreciated. Thanks.

a= 1/2
g(x) = a*x^2

function p(y)
    return -(2a*y-1)^2

function q(x,y)
    return ((2a*y-1)^3-(27a^2)*(x^2))

function del(x,y)
    return (a^2*x^2-2(a*y-1)^3)*x^2

function r(x,y)
    if all(del(x,y) .>= 0)
        return -(a*y+1)./(3a)  
        return (a*y+1)./(3a)

x = range(0, 50, length=100);
y = range(0, 50, length=100);

I wouldn’t do it this way. Just define a function to work on scalar inputs, and then broadcast it. (And it’s good style to avoid non-constant globals, i.e. pass a as a parameter.)


del(x,y,a=1/2) = ((a^2*x^2-2(a*y-1)^3)*x^2
r(x,y,a=1/2) = del(x,y,a) ≥ 0 ? -(a*y+1)/(3a) : (a*y+1)/(3a)

x = y = range(-10,10, length=100)
z = del.(x, y') # 100Ă—100 grid of values for plotting

Get out of the habit (from Matlab or Python or R) of trying to define “vectorized” functions for things that are logically scalar. Scalar functions are fast in Julia, and are easier to work with.

1 Like

Thanks a lot for your answer, it helped. Thank you for the advice as well [beginning to learn Julia].