Piecewise Functions - Challenge Question

1. Use the Piecewise command to reproduce the following plot.

Step 1: Write a function using Piecewise

f1[x_]:=Piecewise[{{1,x<1},{1,x>2}},0]

Step 2: Ensure Plot is working and add option to join discontinuous sections.

Plot[f1[x],{x,0,3},Exclusions->None]

Step 3: Label Graph

Plot[f1[x],{x,0,3},Exclusions->None,AxesLabel->{"t","\!\(\*FractionBox[\(I\), \(\*SubscriptBox[\(I\), \(o\)]\(\\ \)\)]\)"},PlotLabel->"Intensity of Square Wave Generator Output"]

2. Now use the Piecewise command to reproduce the following plot.

From the graph we can read that the function alternates between 1 and 0. Using the piecewise command we can set the function to 0 at all points, apart from the ones we specify. Thus our approach is to begin with a single peak, setting our function to 1 for 0 < x < 1.

g1[x_]:=Piecewise[{{1,0<x<1}},0]

Plot[g1[x],{x,0,2},Exclusions->None,AxesLabel->{"t","\!\(\*FractionBox[\(I\), \(\*SubscriptBox[\(I\), \(o\)]\(\\ \)\)]\)"},PlotLabel->"Intensity of Square Wave Generator Output"]

Clearly, it would take a lot of time to write out where each peak is. If we however note that there is a peak of length 1 at 0, 2, 4, 6, ... we can use the Table command to make a list of the peaks automatically.

gn[x_]:=Piecewise[Table[{1,0+2n<x<1+2n},{n,0,9}],0]

Plot[gn[x],{x,0,20},Exclusions->None,AxesLabel->{"t","\!\(\*FractionBox[\(I\), \(\*SubscriptBox[\(I\), \(o\)]\(\\ \)\)]\)"},PlotLabel->"Intensity of Square Wave Generator Output"]

Note: If I write the function as

gnWRONG[x_]:=Piecewise[{Table[{1,0+2n<x<1+2n},{n,0,9}]},0]

Plot[gnWRONG[x],{x,0,20},Exclusions->None,AxesLabel->{"t","\!\(\*FractionBox[\(I\), \(\*SubscriptBox[\(I\), \(o\)]\(\\ \)\)]\)"},PlotLabel->"Intensity of Square Wave Generator Output"]

I get an error. This is because the output of a Table command is already a list, and therefore there are too many levels of curly brackets in the Piecewise command, i.e.

wrong[x_]:=Piecewise[{{{1,x>0},{2,x<0}}},0]

Plot[wrong[x],{x,-3,3}]