Mathematica Programming

Dennis SilvermanMathematical Physics 212  BU . C .  Irvine

Built-in Programming

Mathematica already has several important built - 
      in programming capabilitiesover and above standard programming languages .

Graphics is immediately  done without having to first output 
      data and then entering a graphics program .

Matrix and vector algebra are built in,  
    saving the usual multiplicativeloops .

Functions are easily defined in place .

Standard functions are automatically calculated without adding
      subroutine links or encoding interpolating functions .

Complicated algebra and complex numbers are automatically 
      handled .

Variables do not always have to be typed or 
      dimensioned .

Differential equations are directly solved numerically without 
      direct programming .

Tables of functions can be directly calculated without having
       to write loops .

Input and Output of Data

?OpenWrite

?OpenAppend

outstream = OpenWrite["temp"]

?Write

Write[outstream, 1]

Write[outstream, 2]

Write[outstream, 3]

Write[outstream, 4]

Close[outstream]

!! temp

readin = OpenRead["temp"]

?Read

Read[readin, Number]

Read[readin, Number]

a = ReadList["temp", Table[Number, {2}]]

Close[readin]

Close["temp"]

\(Type\ assignments\ for\ data\ \(are : \ Byte\), \ Character, \ Real, \ 
    Number, \ Word, 
Record, \ String, \ Expresssion, \ 
    and\ \(Hold[Expression] . \)\)

Assignments in Loops

i++   increment i by 1\(\(i--\)\ \ \ decrement\ i\ by\ \(1
++\) i\ \ pre - 
      increment\ \(i
--\) i\ \ pre - decrement\ i\)i += di   add di to ii -= di   subtract di from ix *= c     multiply x by cx /= c     divide x by c

Loops

?Do

Do[Print[i], {i, 0, 6, 2}]

For a nested loop :

Do[Print[{i, j}], {i, 3}, {j, 3}]

Testing Loops

?While

n = 10; While[(n = n - 1) > 5, Print[n]]

?For

For[i = 1, i < 4, i++, Print[i^2]]

\(start\ and\ body\ can\ be\ multiple\ statements\ separated\ by\ 
      semicolons . 
		Semicolons\ separate\ statements\ that\ are\ executed
      \ without\ displaying\)the results .

Transfers

?Label

?Goto

q = 2; Label[begin]; Print[q]; q += 1; If[q < 6, Goto[begin]]

?Break

?Continue

?Return

If Statements

?If

\(Or\ you\ can\ regard\ this\ in\ Fortran\ 
      \(as : 
		\(If[test, then, else] . \)\)\)

Do[Print[i]; If[i > 5, Break[], Continue[]], {i, 10}]

For nested if statements :

Do[If[i > 2,  If[i == 3, Print[i], Print[10  i]], Print[-i]], {i, 
        5}]

The multiple if transfer statement is :

?Which

i = 4

Which[i < 1, out = 0, i < 4, out = 1, i < 10, out = 2]; out

Compile

?Compile

Modules

?Module