Sie sind auf Seite 1von 11

Mathematica at WWU http://faculty.wwu.

edu/curgus/
http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html
This file is in fact for any Mathematica version from 8 to 12.1

Mathematica at WWU
notes by
Branko Ćurgus

Mathematica at WWU
These notes are written for

which is available in BH 215. This is the latest version that we have.

Getting started
You need to find a campus computer with Mathematica 12 installed on it (for
example computers in BH 215). You will find Mathematica 12 as follows (this
sequence might differ on different campus computers)

        
Start -> Programs -> Math Applications -> Mathematica 12
When Mathematica starts up, it gives you a blank Mathematica file. A
Mathematica file is called a notebook. As you start writing in a blank notebook
Mathematica forms a cell; a thin blue frame will appear on the right of the
notebook window. This is a cell bracket.
Start writing something simple, 2+2 for example. After writing 2+2, hold
down the Shift key and press Enter (this is abbreviated as Shift+Enter). This
tells Mathematica to process your input. The result will appear in an output
cell. Notice that the thin blue brackets of the input and output cells have
differently designed tops.
To add a new cell place the pointer in the notebook window below the last cell.
Make sure that the pointer becomes a horizontal I-beam. Then click and a cell
insertion bar will appear. Only then start typing. By default, new cells are input
cells. To change the style of a cell: click the cell bracket; this highlights the
bracket; then choose style from the menu item Format -> Style

It is essential that there is no text in an input cell. Text and commands


cannot be mixed.

Selected
Processing math: 0%
videos from wolfram.com
http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]
Mathematica at WWU
A good place to start with learning Mathematica are the following videos from
wolfram.com. Please read my comments as well. One general comment: In the
movies below please ignore everything that relates to free-form input. Your
homework notebooks should not contain free-form linguistic input. Only
Mathematica language is allowed for calculations on Assignments.

A movie with Mathematica Basics. Pay attention to these features in this


movie:
01:30-03:10   Functions - basic building blocks of Mathematica language!
Three simple rules of Mathematica language:
1. Functions in Mathematica are Capitalized.
2. Use [ ] to surround function arguments.
3. Use commas , to separate function arguments.
03:14-03:30   I do not use palettes. I think that keyboard input is more
efficient, but you might find palettes useful.
04:10-07:10   Lists and matrices. A matrix is a list of rows. Often we
might encounter a list of lists of lists, and so on. Learn how to recognize
this.
07:18-11:00   Finding a right function.
11:00-12:14   Getting help while working with functions.
This movie is for version 8, but all applies to version 12
First 10 minutes with
Mathematica 8. Pay attention to these features in this movie:
00:45-02:50   Ignore free-form input.
03:23-04:30   Three simple rules of Mathematica language:
1. Functions in Mathematica are capitalized.
2. Use [ ] to surround function arguments.
3. Use { } to denote lists and ranges.
Three important examples are given here: Plot , Factor and
Table . I do not use Factor much; I use Simplify and
FullSimplify much more often.
05:50-06:43   How to use Manipulate.
07:15-07:54   How to create Text Cells, Title. Also learn how to make
Sections, Subsections, Subsubsections.
08:31-10:05   How to use Mathematica documentation.
10:06-end   Ignore free-form input.
A short movie about How to use the suggestions bar.

Movies below are Wolfram movies posted on YouTube. The reason for linking to
YouTube is that I liked these movies and I could not find them at the Wolfram site.
However, you can find many more useful movies at the Wolfram site Getting Started
with Mathematica.

Hands-on start to Mathematica: Notebooks. Pay attention to these features in


this movie:
0:52-2:35   How to create a new notebook and structure it right. This is
exactly the form that you should use for your homework
notebooks. The title will be Assignment 1, the subtitle is your first
and last name, Sections: Problem 1, Problem 2 and so on.
2:35-3:12   How to open and close groups of cell.
Hands-on start to Mathematica: Notebooks. Pay attention to these features in
http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]
Mathematica at WWU
this movie:
0:52-2:35   How to create a new notebook and structure it right. This is
exactly the form that you should use for your homework
notebooks. The title will be Assignment 1, the subtitle is your first
and last name, Sections: Problem 1, Problem 2 and so on.
2:35-3:12   How to open and close groups of cell.
Hands-on start to Mathematica: Methods to get started. Pay attention to these
features in this movie:
0:00-1:01   How to organize your notebook. Exactly as what you need for
Assignments.
01:00-03:36   Ignore free-form input.
3:39-4:30   Four basic rules of Mathematica language, three as listed
above and Shift-Enter rule.
4:30-5:35   Examples of commands in Mathematica language.
5:40-7:35   An ode to Mathematica documentation.
7:40-9:40   Using pallets and keyboard input to write in Mathematica
language.
Hands-on start to Mathematica: Basic calculations. Pay attention to these
features in this movie:
0:45-2:35   Mathematica always performs exact calculations. To get
approximations use N[] . But please, in your notebooks do not use % ,
like in N[%12,10] , to cite results of previous calculations. This is not a
prudent programming practice, since when you reopen your notebook
later these numbers will change, so N[%12,10] can mean something
completely different.
2:45-3:25   Notice that a matrix in Mathematica is just a list of lists.
3:35-5:00   A variable assignment, much better way to deal with
important special values.
5:20-6:50   How to create your own functions. Pay attention to the
underscore and colon in the definition of

f[x_]:=x^2+x+1
My recommendation is to use more complicated names for functions to
avoid duplication and to always clear the string that you are using as the
name. So, a better way here would be to write

Clear[myf,x]; myf[x_]:=x^2+x+1

6:50-7:50   Solving equations: Pay attention to different meaning of


these three symbols = (variable assignment), := (set delayed, used
when defining functions), == (used in equations to be solved).
Hands-on start to Mathematica: Basic graphics. Pay attention to these features
in this movie:
00:25-04:15   Ignore free-form input.
4:15-4:55   Graphing two or more functions is explained here. Pay
attention: two functions are placed in a list.
4:55-6:00   Naming and showing graphics together and using the
function Show[]
6:00-8:05   Using Options[Plot] is a very important part of taking
http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]
Mathematica at WWU
full control of your plots.
Hands-on start to Mathematica: Making interactive models. Pay attention to
these features in this movie:
0:40-3:42   Introduction to Manipulate[] . Pay attention to the color
of what you type and the matching of brackets.
Hands-on start to Mathematica: Complete example. Pay attention to these
features in this movie:
00:00-00:45   Ignore free-form input.
0:45-1:25   Making a list using Table[] is a very important tool. The
list is named data1 and plotted using ListPlot[] .
1:30-2:40   The function Fit[] is used to find the line which is the
best fit for the data. Then, the data and the line are shown on one plot.

Brackets in Mathematica
Before presenting a few examples of how to use Mathematica it is important to
notice that there are five types of brackets in Mathematica:

( ) -- parentheses or round brackets -- for grouping terms --  


((E^(I Pi)) + 1)
[ ] -- square brackets or box brackets -- for enclosing arguments of
functions --   Cos[Pi/5]
{ } -- braces or curly brackets -- use them to put things together in a list --
  {1, 0, Pi, E, I}
[[ ]] -- double square brackets -- use them with lists --  
{1, 0, Pi, E, I}[[4]]

          (The double square brackets will appear nicer if you type   Esc[[Esc  
and   Esc]]Esc.)
(* *) -- starred parentheses -- for comments in Mathematica code --  
(* this is a comment *)
Each example below uses some (or all) of these brackets. Please pay
attention and make each example a learning experience.

What to do if things go wrong?


Eventually things will go wrong. Mathematica might stop responding. When this
happens, there are 6 ordered actions that you can do to remedy things. Start with
the first action, then proceed to the next one until Mathematica responds.

1. Abort evaluation in theEvaluation menu; the keyboard shortcut is Alt+.


(This means: hold down the Alt key, then press the . key.)
2. In Evaluation menu chose Quit kernel , then click Local .
3. Activate the Windows Task Manager by the keyboard shortcut Ctrl+Alt+Del ,
then select Processes tab. Highlight MathKernel.exe in the Processes list and
click End Process .
4. Exit the Mathematica notebook in the File menu; the keyboard shortcut is

http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]


Mathematica at WWU
Ctrl+F4 .
5. Activate the Windows Task Manager by the keyboard shortcut Ctrl+Alt+Del ,
then highlight Mathematica in the Applications list and click End Task .
6. Power off your computer

Random, but important remarks


Pay attention to the difference between ; and , . For example, if your cell
contains several items, then the items should be separated by ; (not , ). To
separate elements of a list one uses , , as in the above example
{1, 0, Pi, E, I} .

Mathematica, like all good software, has a lot of


shortcuts
Here I list shortcuts that I use often. Below Key1+Key2 means that you press
Key1 and Key2 two together, while Key1-Key2 means that you press Key1
then Key2 . When we use letter keys, then we do not write - between them. For
example, Esc-pi-Esc means that you should press the Escape key then p, then i,
then the Escape again. This is the shortcut for the Greek lower case \pi. I use
capitalized Key1 , since the names of all named keys on a keyboard are capitalized.
In describing keyboard shortcuts below, I use lover case letters as names of
alphabet keys. When I write a capital letter that means that one has to use the
Shift key, as you would to type a capital letter.

Just   Alt+9   opens a new Input Cell.


Just   Alt+7   opens a new Text Cell.
With the cursor in an Input Cell,   Shift+Enter   evaluates that cell. The
  Enter   key on the numeric pad is equivalent to   Shift+Enter  
Just   Enter   starts a new line in a cell.
Use   Ctrl+6   to write exponents
Use   Ctrl+2   to write square root
Use   Ctrl+/   to write fractions
Use   Esc-[[-Esc   to write left double square bracket
Use   Esc-]]-Esc   to write right double square bracket
Use   Alt+.   to stop evaluation
Use   Alt+;   to check spelling
Use   Ctrl+F6   to cycle through the open notebooks
Use   Alt+4   to open a section title cell
Use   Alt+5   to open a subsection title cell
Use   Alt+6   to open a subsubsection title cell
In a Text Cell use   Esc-elem-Esc   to write  ∈  which is an "is element of"

http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]


Mathematica at WWU
symbol
In a Text Cell use   Esc-dsZ-Esc   to write  ℤ  which is a standard symbol for
the set of all integers.
In a Text Cell use   Esc-dsR-Esc   to write  ℝ  which is a standard symbol for
the set of all real numbers.
Use Alt+v o to evaluate the entire notebook. The menu equivalent is:
Evaluation , then Evaluate Notebook .
Use Alt+c l (Alt-ce el) to delete all output. The menu equivalent is: Cell ,
then Delete All Output .

Arithmetic in Mathematica
You can use Mathematica as a calculator. For example to get the circumference
of a circle circumscribed about a square with side 1, you type

Pi*2^(1/2)
and Shift+Enter.
To get a numeric approximation type

N[Pi*2^(1/2)]
and, as always, Shift+Enter.
For more see Mathematica's
Arithmetic page.

Mathematical functions and their explorations


Mathematica has hundreds of built in functions. Function names are always
capitalized, for example the standard ones

Exp[x], Log[x], Sin[x], Cos[x], Abs[x], ...


or some which are for some mysterious reason absent from our curriculum:

Sign[x], Floor[x], Ceiling[x], UnitStep[x], ...


Please see the menu item

        
Help -> Built-in Functions -> Mathematical Functions
I view all Mathematica commands as functions with several variables. Some
examples are below.
To plot one period of the sine function

Plot[Sin[x],{x,0,2*Pi}]
Here Sin[x] is one variable, and the domain {x,0,2*Pi} is another
variable. But this function can have many more variables. Options[Plot]
will give you all.
Plotting two functions with several options:

Plot[
http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]
Mathematica at WWU
    {Sin[x],Cos[x]}, {x,0,2*Pi},
      PlotStyle->{{Thickness[0.007],Blue},
{Thickness[0.007],Green}},
      PlotRange->{-2,2}
    ]
Plotting a function of two variables:

Plot3D[ Sin[x]*Cos[y], {x,0,2*Pi}, {y,0,2*Pi} ]


plots a function of two variables.
Find a derivative

D[Sin[3 x]^2 + Cos[4 x], x]


finds the derivative with respect of x.

Simplify[D[Sin[3 x]^2 + Cos[4 x], x]]


finds an algebraically simpler form of the previous answer. Sometimes
FullSimplify[] gives more desirable results.
Integrate[-4 Sin[4 x] + 3 Sin[6 x], x]
finds an antiderivative.

Table[Sin[x + s],{s, 0, 2 Pi, Pi/20}]


produces a list of forty-one shifts of the sine function.
To plot all the functions from the previous item we need to use
Evaluate[] :
Plot[ Evaluate[Table[Sin[x + s],{s, 0, 2 Pi, Pi/20}]],
{x, 0 , 2 Pi} ]
Notice that exchanging the positions of Plot[] and Table[] and
replacing Table[] with Manipulate[] gives a different but useful
result:

Manipulate[
   Plot[Evaluate[Sin[x + s]], {x, 0 , 2 Pi},
      PlotRange->{{0 , 2 Pi},{-1.2,1.2}}] ,
     {s, 0, 2 Pi, Pi/20, ControlPlacement -> Top} ]
Often it is useful to define our own functions. It is a good practice to clear the
name that you use for the function and the name of the variable before the
definition:

Clear[ff,x];
    ff[x_]:= 1- 2 Exp[(x^2)(Cos[x]-1)]
But much more complicated functions are common. For example functions that
include graphing commands.
The zeros of the function cannot be determined exactly. The first positive zero
is close to 1. To find its numerical approzimation we use

FindRoot[ff[x] == 0, {x, 1},


    AccuracyGoal -> Infinity, PrecisionGoal -> 12,
    MaxIterations -> 1000, WorkingPrecision -> 16]
http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]
Mathematica at WWU

Usually we do not need this level of precision, but it is nice to know how to
achieve it. Other positive zeros come in pairs around even positive multiples of
\pi. Here is the pure function combined with Map[] which finds the first 12
pairs

{x /. FindRoot[ff[x] == 0, {x, 2 # Pi - .1},


    AccuracyGoal -> Infinity, PrecisionGoal -> 12,
    MaxIterations -> 1000, WorkingPrecision -> 16],
x /. FindRoot[ff[x] == 0, {x, 2 # Pi + .1},
    AccuracyGoal -> Infinity, PrecisionGoal -> 12,
    MaxIterations -> 1000, WorkingPrecision -> 16]} &
/@ Range[1, 12]
The same outcome produced with Table[] is
Table[
 {x /. FindRoot[ff[x] == 0, {x, 2 k Pi - .1},
    AccuracyGoal -> Infinity, PrecisionGoal -> 12,
    MaxIterations -> 1000, WorkingPrecision -> 16],
  x /. FindRoot[ff[x] == 0, {x, 2 k Pi + .1},
    AccuracyGoal -> Infinity, PrecisionGoal -> 12,
    MaxIterations -> 1000, WorkingPrecision -> 16]},
       {k,1, 12}]
Notice the use of semicolon ( ; ) in a cell. Its purpose is to separate different
commands used in the same cell. Contrast this with the use of comma ( , )
which is used to separate variables in a command which takes several
variables.
Also notice the use of colon ( : ) in the definition of function. For the meaning
of := check SetDelayed in the help file. Basically, if you use := , then
Mathematica will remember the formula and evaluate it only when we use the
function later on. I prefer to use := in definitions of functions, in particular
complicated ones. Often, like in the simple example above, := and = are
interchangeable. However, this is not always the case. Here is one example in
which = yields a meaningful function while := does not make sense: Say I
want to graph three random lines with y-intercepts and slopes in the interval
[0,1]. I can define

Clear[f1, f2, f3, x];


    f1[x_] = Random[] + x*Random[];
    f2[x_] = Random[] + x*Random[];
    f3[x_] = Random[] + x*Random[];
Now you are thinking that I defined the same function each time. Try graphing:

Plot[
    {f1[x],f2[x],f3[x]}, {x,-5,5},
      PlotStyle->{{Thickness[0.007],Red},
{Thickness[0.007],Green}, {Thickness[0.007],Blue}},
      PlotRange->{-5,5}, AspectRatio->Automatic
    ]
and you will see that these are different functions since in each definition
Mathematica assigned different random numbers as slopes and y-intercepts. I
am writing all of this to point out that

Clear[g,x];
    g[x_]:= Random[] + x*Random[];

http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]


Mathematica at WWU
does not make sense! With this definition Mathematica selects random
numbers as slope and y-intercept whenever you calculate. For example,
g[1] . Try evaluating it twice. You get different numbers! Thus, as defined,
g[x] is not a function.
The function sinc
is in Mathematica's huge library of functions. Clearly Sinc
is not a bijection. However, in the spirit of inverse trigonometric functions one
can define ArcSinc[x] by restricting the domain for the independent
variable x . This is a nice exercise is using Interpolation[] function in
Mathematica.

Recursively defined functions


Functions whose domain is the set of positive integers can be defined
recursively. Here is an example. Why I choose this long name Repeat will be
clear after you define and explore this function.

Clear[Repeat, n];
    Repeat[1] = 1;
    Repeat[n_]:= Repeat[n - Repeat[n - 1]] + 1
But much more complicated functions are common. For example functions that
include graphing commands.
If you try to calculate Repeat[100] you will notice that Mathematica takes
quite a long time to calculate this number. Try

Timing[Repeat[60]]
On my computer it takes 2.735 seconds to calculate that
Repeat[60] = 11 . The reason for this is that as defined above the
function Repeat[] does not
remember any values that it calculates. We can
make Mathematica remember all the function values it finds by changing the
syntax in the definition:

Clear[Repeat, n];
    Repeat[1] = 1;
    Repeat[n_]:= Repeat[n] = Repeat[n - Repeat[n - 1]]
+ 1
You will easily notice that this definition is much faster.
Test what this function does using

Table[Repeat[k], {k, 1, 106} ]


or by plotting its graph (which consists of points with integer coordinates)

Show[
   Graphics[{
    {PointSize[0.015], Table[Point[{k, Repeat[k]}],
{k, 1, 106}]}
          }],
   PlotRange -> {{0, 107}, {0, 15.5}},
   Frame -> True, ImageSize -> 400
     ]
But sometimes we want to control more details of the plot:

http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]


Mathematica at WWU
Show[
  Graphics[{ (* the start of the graphics, it is a
list *)
    { (* the grid lines are in this list *)
    Thickness[0.003], GrayLevel[0.8],
    Table[Line[{{0, j}, {107, j}}], {j, 1, 15}],
    Table[Line[{{j(j + 1)/2, 0}, {j(j + 1)/2, 16}}],
{j, 1, 15}]
    }, (* the next list are the points on the graph*)
    {PointSize[0.015], Blue, Table[Point[{k,
Repeat[k]}], {k, 1, 107}]}
         }], (* the end of the graphics *)
   PlotRange -> {{0, 107}, {0, 15.5}},
   AspectRatio -> 1/2,
   Frame -> True,
   FrameTicks -> {Table[j(j + 1)/2, {j, 1, 15}],
Range[1, 15], {}, Range[1, 15]},
   ImageSize -> 400
     ]
Please notice the indentation of the parts of the command. That helps me keep
me identify the code for each part of the picture. You can copy-and-paste (^C
then ^V) this gray box into your Mathematica notebook.
I used the Repeat[] function above as an illustration for a recursive
definition. But there are explicit formulas that define the same function. Such
formulas are called "closed form expressions" for a recursive sequence. Here
are few closed form expressions for Repeat[] :

Clear[Rf1, Rf2, Rf3, n];


    Rf1[n_]:= Round[Sqrt[2*n]];
    Rf2[n_]:= Floor[(1/2) + Sqrt[2*n]];
    Rf3[n_]:= Ceiling[(-1/2) + Sqrt[2*n]];
The following table is a quite convincing evidence of the above claim:

Table[
       {k, Repeat[k], Rf1[k], Rf2[k], Rf3[k]},
                                              {k, 1,
100}
     ]//TableForm
I just want to mention that the determining a closed form expression for a
recursive sequence is a hard problem. For example, the creator of Mathematica
Stephen Wolfram in 2002 introduced the following slight modification of the
Repeat[] sequence:
Clear[W, n];
    W[1] = 1; W[2] = 1;
    W[n_]:= W[n] = W[n - W[n - 1]] + 2
I believe that I am the first one to come up with a closed form expression for
this sequence. On February 10, 2011 I found the following closed form
expression for the above sequence

Clear[Wf1, n];
    Wf1[n_]:= 2*Floor[Sqrt[n]]-
(-1)^(n+Ceiling[Sqrt[n]])

http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]


Mathematica at WWU

http://faculty.wwu.edu/curgus/Courses/Mathematica/Mathematica_12.html[8/17/2020 12:41:53 PM]

Das könnte Ihnen auch gefallen