Assisted Computing with Mathematica

The basics
1. Things that you type are placed into blocks called “cells”. The hierarchy of cells is indicated along the right edge of the notebook by square brackets. Cells can have subcells. The shape of the bracket can be used to ascertain whether a cell is mere text, like this one, or whether it is an “input” cell, an “output” cell, etc. Specifically, the top of the bracket looks different.
Cells can have multiple “lines” (which is what this single line is).

This is a text cell. It has 2 parallel horizontal lines on the top of the bracket. The next two cells are an input (triangle), and an output (triangle with line), respectively. Note that these cells are all subcells. The larger container cells are just normal square brackets.

a=1+4

2. “Undo” and “Redo” hardly work at all. Don’t delete something, then change your mind, and hope to get it back. Copy and paste also have severe restrictions on what they do correctly. Deleting cells can only be done by deleting the cell bracket itself. Deleting the contents of a cell does not delete the cell. 
3. Broadly speaking, Mathematica is unlike some other computational tools in that it doesn’t do anything “on the fly” (for example, Excel). Here, when you change a cell, nothing happens! When you add a new formula, nothing happens! When desired, you instead have to ask Mathematica to act on the parts that you want it to act on. This leads to some serious confusion. For example, go above to the input cell and change the “4” to some other number. Sadly, you’ll notice that the so-called “answer”, “5”, doesn’t change. It is extremely easy to look at a notebook and come away with wrong ideas about the problem you’re working on simply because the answers are out-of-date. In fact, it’s possible that you are still seeing things that are answers to questions that have themselves long been deleted!
4. While we’re on the topic of evaluations, it’s possible for your notebook to be affected by things that happened in other Mathematica notebooks that are long gone, too. Crosstalk between different documents is possible. If one notebook says that a is 5, then a is 5 in all currently open notebooks, too! There are a couple of ways to help prevent that. First, the following line in an input cell clears out all the old stuff that you thought was already gone anyway. It doesn’t make everything right, it just makes it so that other closed notebooks can’t hurt you. You should start every notebook and also every specific problem with a fresh copy of this line.

ClearAll["Global`*"]

Typically, you will place this command into a notebook more than once... you'll use it over and over again to keep a lower section of a notebook (like problem #2 on a homework assignment) separate from an upper section of a notebook (like problem #1 on that assignment).

Similarly, Mathematica sometimes loses track of what it's supposed to be remembering, and what it's not. Under the "evaluation" tab on the menu bar, you'll find an option called "quit kernel". You can use this to get a fresh restart when something freezes.

5. When you enter stuff, you can't use the enter key. Here are some forms of how to "enter" something. Also, the form of your enter key can also be used to control the type of cell you are making. 
  a. Use "regular" enter to merely accept a line, and then also create a new line within the cell, but don't have Mathematica act on anything.
  b. Use shift-enter to create and complete an input line and then also evaluate it.
  c. Use the down arrow to accept a line, and then exit the cell without evaluating it or making a new line
  d. Use ctrl-a to "select all". Once you see that all the cells are selected (highlighted brackets on the right), then use shift-enter (see above) to evaluate the entire notebook. 
This 4 key combination (ctrl/a then shift/enter) is pretty much the standard "enter" key that you'll want while you're working on a notebook.
Before you submit anything for this class, you MUST type this 4-key combination as the very, very last edit of your notebook.
Then you should therefore save your notebook only AFTER running the entire notebook.
It's the first thing I'll be doing when I open your notebook, and often times this just deletes stuff that you thought was still there, but which is actually out-of-date leftovers.

Using Inputs and Outputs
Virtually every time you evaluate an input cell, Mathematica automatically creates a corresponding output cell. For example, I didn't create the output cell containing "5" above, it just appeared when I used shift-enter on the input line containing "1+ 4". Often, you actually want immediate results like that. Other times you don't. For example, suppose you want to define a new variable "g", and set it equal to 9.8"

g=9.8

I used shift-enter to evaluate this cell, so the output cell was created automatically. Why did I want to “evaluate” it? In this case, evaluating it tells Mathematica to remember that g is 9.8 from now on, so that “g” can be used in later calculations.  Each output cell shows the result from the previous input cell. For example, I’ll evaluate a new input cell:

2*g

You can see that it used “g” correctly here. That would not have happened if I had merely “entered” g above instead of “evaluating” it. 
However, it’s tedious to see two copies of your basic definitions like this all the time. To evaluate something without displaying it in a new output cell, add a semicolon to the end of the input line:

G=6.67E-11;

Sometimes, you’ll have a lot of results being displayed as a pile of numbers that are hard for a human to read (see the 3, 12, 17 below and imagine that there are 22 numbers instead of just 3!) You can use the “Print” command to help organize these results. What would be nice for a human reader is to see the name of each result along with its value:

x=3    (* this light-blue syntax (i.e., parenthesis-star) at the end of a line is a "comment", ignored by Mathematica *)
y=4*x
z=5+y
Print["The value of x is ",x]
Print["The value of y is ",y," Newtons."]
Print["The value of z is ",z,", which is 5 + ",y]

Regarding units, we'll treat variables as "pure" numbers", so g = 9.8; it's up to YOU to remember that it's actually g = 9.8 m/(s^2).

Let’s start to evaluate some functions. As you see already, everything in Mathematica is case-sensitive. Functions all use [square brackets] to specify their arguments. Pre-made functions all start with capital letters, and in fact use capital letters for “intermediate” words, too, like “ArcTan”:

ClearAll["Global`*"]  (* this ClearAll is here to erase the fact that x=3 from above, and just keep x as a variable in subsequent work *)
y[x_]=x*Sin[x]

Since I didn’t use a semicolon, it repeated the result back to me. Also, you’ll sadly note that when you define the arguments in a function, you have to follow them with an underscore. But when you use the arguments, you write them normally... without an underscore. Notice also that the asterisk disappeared. 
In most cases, Mathematica knows that a space is the same as a multiply, so no asterisk is even necessary:

y2[x_]=x Cos[x]

However, xy is different than x y, because "xy" is just a new variable that happens to be two letters long.

You’ve probably noticed by now that Mathematica keeps adding little “In[##]” and “out[##]” labels beside every input and output cell when they are evaluated. They are numbered based on the order that they were evaluated since you started this Mathematica session. These labels don’t have any significant use for us, and they never will. 

Let’s create some more complex expressions. You can use “Excel” notation (e.g., x^2), but in most cases, you can make a prettier version using a control key. For example, shift-6 (“^”) is “to the power of”, but ctrl-6 actually makes a real math superscript. The same is true for fractions (use ctrl-/), subscripts (ctrl-_), square roots (ctrl-2, which is not obvious), etc. To learn (and even use) some of these shortcuts, turn on the Basic Math Assistant using the “Pallets” menu. Highlight a region before specifying an operator to make sure that you include all the parts you want. To exit a “mode” (say, superscript mode) without using the mouse, you use the right-arrow key.

(Subscript[q, 1])=(x^2)+(y^(2 )); (Subscript[q, 2])=x+((x^2)/3);(Subscript[q, 3])=((x+(x^2))/3);

You can also see that I can put multiple definitions on one line if they are separated by semicolons. 
Often, you need to create Greek characters. Each Greek character has a standard corresponding English character assigned to it. A is for Alpha, B is for Beta, G is for Gamma. These are case sensitive. So, D → Δ, but d→ δ. To show a Greek character, you use a 3-key sequence: ESC-letter-ESC. The escape key is usually on the upper left corner of your keyboard. You must memorize these Greek versions of a, b, g, q, f, y, p, w, and s, at a minimum, before exam #1. 
Let’s ask Mathematica what π is:

π

As you can see, it didn’t really do what we wanted. Generally, Mathematica usually shows the most fully accurate and simplified version of any request that it can think of, and there’s nothing more accurate than just leaving it as π. The function “N” gets Mathematica to tell you a Number:

N[π]

Compared to other “programming” environments, Mathematica is unusual in that it has a lot of single-letter function names like “N”. That’s a little sad, because what that means to us users is that we can’t use “N” as a variable in any of our calculations. In fact, the makers of Mathematica believe that users should never, ever, use any variable names that start with Capital letters, because most of them already mean something else. This is just another example of the tail wagging the dog, but I guess we have to live with it.

What if we wanted more significant digits for π? A second argument can be added to the function “N”:

N[π,20]

Arguments can also be variables:

dig=30; N[π,dig]
N[E,dig]

Here, the “Exponential” symbol e is not a normal “e” from the keyboard, but is, sadly ESC-ee-ESC. You have to use two “e” characters, because a single “e” would give us a Greek epsilon: ϵ. 

Let’s do some simplifications and so on.

Simplify[((30-x-(x^2))/(5-x))]

Expand[(5+x) (2-x)]

One thing it can also do is solve algebraic equations for you, whether symbolically or numerically. This is especially nice if you want the (numerical) answer to a problem that has no algebraic solution. Suppose I want to solve the formula x*sin(x) = 6 for x. Here’s one of many ways to do it:

result=FindRoot[x*Sin[x]==6,{x,0.01}]

In the formula, I have to use a double-equals “==” for the equation. The second argument (inside the {curly brackets}) is used to tell Mathematica what to solve for (in this case, “x”). Also included in the curly brackets is an initial guess for x. I thought maybe x would be 0.01, but Mathematica said it was 7.25. So, my guess was not so good. Sometimes, you need very good guesses, other times, it doesn't matter much. Strangely, it wouldn’t let me put in  zero for my guess, because that resulted in a divide by zero somewhere behind the scenes. 

A problem with the "result" given by Mathematica is that it isn’t “mathematical”. For example, if I multiply it by 2, I get nothing useful:

2* result
2.0 * x

We could tell that the answer was non-mathematical because it contained an arrow instead of an equals, and because it was enclosed in curly brackets. The arrow means it’s a “rule” (with no obvious connection to the standard English meaning of the word “rule”) instead of a number, and the brackets mean it’s an array (which Mathematica calls a “list”). Sadly, the list generated above is a list even though it only contains one item. So we have to go through some rigamarole to transform {x->7.25663} into an obviously more desirable x = 7.25663 (i.e., we have to transform a rule into a value, and also a list into a scalar). The function that does this is called “ReplaceAll”. 
Here are three equivalent ways of using "ReplaceAll" for this problem to get  a real number for x.
Recall again that so far, result = {x->7.25663}

ReplaceAll[x,result]
(x/. result)
(x/. {x->7.25663})  (* Here, I manually replaced "result" with what "result" stands for *)

As you can see, there is a shorthand-notation for “ReplaceAll”, commonly called “slash dot”, that does the same thing with less typing.They all mean “use “result” to replace x with 7.25663”.

ClearAll["Global`*"]

Plotting

Let’s plot this same function to see whether the above answer makes sense:

f1[x_]=x Sin[x]-6;
Plot[x Sin[x]-6,{x,0,20}]

It seems like there are actually a lot of roots for this equation! The next one seems to be a little larger than 8...

N[FindRoot[x*Sin[x]-6==0,{x,8}]] (* this is the same as above, but with a different starting guess *)

The next one is larger than 13:

N[FindRoot[x*Sin[x]-6==0,{x,13}]]

In summary, even though Mathematica is smart, you still have to be smart enough to ask the right question. 

We can manipulate the properties of a plot, such as aspect ratio, etc., but only if you know zillions of little commands to type in. One way to learn the commands is to double click on a plot, and change the thing you want. However, this method can only be used to learn one feature at a time, and you’ll still have to go through all the tedious work of typing in the formatting commands one at a time, manually. 
Here, I’ll start with a new copy of the plot and modify it using some of the options that appear. When you do this, Mathematica unfortunately creates a second copy of the plot: one is the untouched original, and the second has the one new feature added in. To make this final plot, I originally had to make a dozen plots, and then delete all but the last one manually. Besides the “features” illustrated here (like FrameStyle, Thickness, etc.), there are zillions more editable properties!

Plot[x Sin[x]-6,{x,0,20},ImageSize->{600,250},AspectRatio->Full,PlotStyle->Directive[RGBColor[0.8,0.2,0.1],AbsoluteThickness[2.8],Dashed],Frame->True,FrameTicks->{{Automatic,None},{Automatic,None}},FrameStyle->Directive[RGBColor[0.05,0.1,1],AbsoluteThickness[1.4]],Background->RGBColor[0.6,0.9,0.8]]

Not that you would want these specific choices; in fact, they’re terrible. But, you can just add another comma in the plot command and start typing in more properties. Again: TYPING (not clicking) is the only way to permanently “modify” properties. 
You probably noticed when you were playing with the modification menus that it would make a modified plot of a modified plot, and so on. Did you notice the use of the “%” sign near the beginning of each line?That means that it’s basing this iteration on a previous result (an In##), which may not be valid if you go back and make changes to something earlier. You should never submit any work for this class that refers to a prior In##. That’s because when I run it, I’ll have different numbers than you had!

Also, Mathematica makes it pretty hard to add and control axis labels for plots. There are many ways to do it, and none of them are that great. Here’s one: use the “Labeled” function on the plot itself:

Labeled[Plot[x Sin[x]-6,{x,0,20}],{"time (s)","Power (W)"},{Bottom, Left},RotateLabel -> True]

Other ways to manipulate axis labels are based on the idea that the labels aren’t part of the plot itself, but of the “Frame” (the whole teal box in the plot a little higher up, which extends outside of the plot itself). While you’ll find that Mathematica’s built-in help menu is so cryptic as to be worthless, you can use the internet to find other people to help you figure stuff out. Common sources of help are “mathematica.stackexchange.com”, and “reference.wolfram.com”. The first is often very helpful, but users of the second site usually assume you’re an expert already, and will usually be demeaning to newbies.

ClearAll["Global`*"]

Contour Plots

	Let’s create some contour plots, which are like weather maps. First, let’s define a temperature function:

ϕ[x_,y_]=(x^2)-(y^2);ψ[x_,y_]=2*x*y;

In this definition, suppose that ϕ is a temperature field. I have defined ψ as a separate but related field representing the direction of heat flow due to conduction; if done correctly, it is a set of lines that is everywhere perpendicular to the isotherms defined by ϕ.
Let’s first just plot the ϕ field:

ContourPlot[ϕ[x,y],{x,-5,5},{y,-5,5},Contours->20,ColorFunction->"Rainbow"]

Next, let’s plot the ψ field:

ContourPlot[ψ[x,y],{x,-5,5},{y,-5,5},Contours->20]

Sadly, it’s colored, although it’s always improper to color a ψ plot. So, I’ll need to uncolor it later.

Next, let’s plot the two of them together. We need to learn two new things here: one is how to combine them, and the other is how to make sure that only one of them has the plot colored in, so that when you lay them on top of each other, the colors from the upper plot don’t cover and conceal the lower plot. 
To combine them, I’ll assign a variable name to each plot command itself, and then use the “Show” command to display both together.

plot1=ContourPlot[ϕ[x,y],{x,-5,5},{y,-5,5},Contours->20,ColorFunction->"Rainbow"];
plot2=ContourPlot[ψ[x,y],{x,-5,5},{y,-5,5},Contours->20, ContourShading-> None];

Show[plot1, plot2]

We could make a third plot that is a vector plot showing the direction of heat flow. Obviously, this should be related to the function ψ. For the functions above, the x and y velocity components turn out to be:

vx[x_,y_]=2*x;vy[x_,y_]=-2*y;
plot3=VectorPlot[{vx[x,y],vy[x,y]},{x,-5,5},{y,-5,5},VectorColorFunction->None,VectorStyle-> Black]

Show[plot1,plot2,plot3]

ClearAll["Global`*"]

Parametric/Revolution Plots

A parametric plot is like a contour plot... except that while we want to have a plot that exists in some xy plane, the function is defined in terms of some other variables. A pretty common kind of parametric plot is a function defined in terms of r and θ instead of x and y. For example:

A[r1_,θ1_]=(r1^2)Sin[θ1]+r1;

Here, we really only want to plot A, but it’s hard because plots are generally rectangles with x being horizontal, and y being vertical. The “viewpoint” is a specification of the camera. If the camera is too close, the image gets distorted. I’m hoping ∞ is not too close...

RevolutionPlot3D[A[r1,θ1],{r1,0,6},{θ1,0.6π,2.2π},MeshFunctions->{#3&},ColorFunction->"Rainbow",Lighting->"Neutral",ViewPoint->{0,0,∞},PlotPoints->30,PlotRange->{{-6,6},{-6,6},{-200,200}}]

ClearAll["Global`*"]

Derivatives

There are two ways to do derivatives. The function “D” is for derivatives. You have to tell it the name of the “with respect to” variable.

D[4 (x^3),x]

Since single-letter functions like “D” are awkward in all communities except Mathematica, we have other more readable versions of the same command, available on the basic math assistant palette:

(∂_x)(3(x^2))(* here the "partial" symbol with a subscript "x" just means ((d )/dx). Also, I had to add parenthesis to include the (x^2) part *)

Similarly, “Integrate” has a very similar syntax:

Integrate[5 (x^3),x]

Using the math assistant, you can draw a nicer looking integral:

∫2(x^2)\[DifferentialD]x

You can also set limits of integration by adding curly brackets and two more values for the integration range. Here is the same integral repeated three times: once “indefinite” and two as “definite”:

Integrate[3 x,x]
Integrate[3x,{x,0,2}]
(∫_0^2)3x\[DifferentialD]x

Conditional Functions

Consider a function for the voltage of a capacitor  that is steady at 10 V for 5 seconds, and then a switch is thrown to allow it to discharge through a resistor. If we want to completely describe the voltage both before and after the switch is thrown, we need an “if”:

V[t_]=If[t<5,10,10*(E^(-(0.7)*(t-5)))];
Plot[V[t],{t,0,20}]

A Useful Function: ArcTan[ / ] vs. ArcTan[ , ]

Consider a vector that has known components Vx and Vy. We already know that there an infinite number of results for any inverse trig function, and any machine can only give you one of them... presumably, the one that’s most likely.
The problem with Arctangent is that it wants a ratio... (Vy / Vx). Suppose that Vx = +5, and Vy = -7. This vector is in the 4th quadrant. (Vy / Vx) = -1.4, and the result is -54 degrees. 
Unfortunately, if Vx = -5 and Vy = +7, the ratio is again -1.4, but this time the vector is really in the second quadrant. But, ArcTan (on any computer) tells you that the answer is still in the 4th quadrant. Most software allows you to solve this dilemma by letting you specify the two components separately. In Excel, etc. you use the “atan2” function (theta = atan2(Vx,Vy). In Mathematica, you use the regular ArcTan function, but instead of giving it a ratio, you use a comma to separate the two components. In the following examples, I’ve converted it into degrees for your convenience. The first case is wrong, the second case is correct. You could fix the first case by adding 180 degrees to the result.

Vx=-5;Vy=7;
θ=N[ArcTan[Vy/Vx]*180/π]  (* this is not right because I am specifying only the ration, so Mathematica can't tell which component is negative *)

Vx=-5;Vy=7;

θ=N[ArcTan[Vx,Vy]*180/π] (* this is better: you use a comma to separate the components directly. In Mathematica, "x" is listed first. *)