Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Graphing Plot?

Tags:

wolframalpha

I am trying to graph two functions, but i want to graph one function for a condition but graph using another function if another condition is met.

A simple example would be:

if x > 0 then sin(x) else cos(x)

It would then graph cos and sin depending on the x value, there being an obvious gap at x = 0, as cos(0) = 1 and sin(0) = 0.

like image 307
razr32 Avatar asked Oct 20 '22 06:10

razr32


1 Answers

EDIT: There is a built-in way. I'll leave my original answer below for posterity, but try using the piecewise() function:

plot(piecewise(((cos(x),x<0), (sin(x), 0<x))))

See it here.


I would guess that there's a built-in way to do this, but I don't know it. You can multiply your functions by the Heaviside Step Function to accomplish this task. The step function is 1 if x > 0 and 0 if x < 0, so multiplying this into your functions and then summing them together will select only one of them based on the sign of x, that is to say:

f(x) := heaviside(x) * sin(x) + heaviside(-x) * cos(x)

If x > 0, heaviside(x) = 1 and heaviside(-x) = 0, so f(x) = sin(x).

If x < 0, heaviside(x) = 0 and heaviside(-x) = 1, so f(x) = cos(x).

See it in action here. In general, note that if you want the transition to be at x = a, then you could do heaviside(x-a) and heaviside(-x+a), respectively. If you want N functions, you'll have to have (N-1) multiplied step functions on each term, each with their own (x-a_i) argument. I hope someone else can contribute a cleaner solution.

like image 166
kevinsa5 Avatar answered Oct 22 '22 21:10

kevinsa5