Back: Programming
Next: Pattern Matching; using Head and tests

Programming in Mathematica

Avoid Procedural Loops

You used the general-purpose ``DO'' loops in Fortran and ``for'' loops in C. Forget all that; in Mathematica there are functions which accomplish your tasks more directly. Array arithmetic is done implicitly. Table creates arrays with calculated values. Nest and Fold iterate a given function. Map and Apply perform functions on a list. Sum does S and Product does P.

Table


listA  =  Table[ {i, i^2}, {i,3,5} ]

	{{3, 9}, {4, 16}, {5, 25}}


matrA = Table[ Sqrt[10i+j], {i,1,4}, {j,3,6} ];
matrA // MatrixForm

	Sqrt[13]     Sqrt[14]     Sqrt[15]     4

	Sqrt[23]     2 Sqrt[6]    5            Sqrt[26]

	Sqrt[33]     Sqrt[34]     Sqrt[35]     6

	Sqrt[43]     2 Sqrt[11]   3 Sqrt[5]    Sqrt[46]


Map


Map[ f, { a,b,c,1,2,3 }  ]

	{f[a], f[b], f[c], f[1], f[2], f[3]}


listA
Map[ f, listA ]
Map[ f, listA, {2} ]

	{{3, 9}, {4, 16}, {5, 25}}

	{f[{3, 9}], f[{4, 16}], f[{5, 25}]}

	{{f[3], f[9]}, {f[4], f[16]}, {f[5], f[25]}}


f  /@  { a,b,c,1,2,3 }

	{f[a], f[b], f[c], f[1], f[2], f[3]}


Apply


listB = {W, X, Y, Z};
FullForm[   listB    ]

	List[W, X, Y, Z]


thingB  =  Apply[Plus, listB]
FullForm[   thingB   ]

	W + X + Y + Z

	Plus[W, X, Y, Z]



Times  @@ (listB+1)

	(1 + W) (1 + X) (1 + Y) (1 + Z)


Sum, Product


Sum[ x^i, {i,3,16,4} ]

	 3    7    11    15
	x  + x  + x   + x


Product[ (j-x), {j,4} ]

	(1 - x) (2 - x) (3 - x) (4 - x)


{NSum[ Sqrt[k], {k,10} ],   NProduct[ k, {k,6} ]}

	{22.4683, 720.}


For and Do available, if desperate


For[ i=0, i<5, i++, Print["....line number ", i ]]

	....line number 0
	....line number 1
	....line number 2
	....line number 3
	....line number 4


Do[ Print["(k, k^2+1)   =   ",{k,k^2+1}], {k,2,4}]

	(k, k^2+1)   =   {2, 5}
	(k, k^2+1)   =   {3, 10}
	(k, k^2+1)   =   {4, 17}