Wolfram ResearchProductsPurchasingServices & ResourcesAbout UsOur Sites

How Do I Create Functions with Mathematica?

While Mathematica comes with hundreds of predefined functions, one of the most powerful aspects of Mathematica is that it allows you to create your own functions for operations that may not be predefined.

A Basic Function

To define a function in Mathematica, give the function a name, identify the variables, and determine its output. The following example defines a polyfunction function. Notice the underscore to the left of ": =", which allows a value to be passed to the function definition.

[Graphics:Images/index2_gr_41.gif]

You can now evaluate this function with any input, and the appropriate expression will be returned.

[Graphics:Images/index2_gr_42.gif]
[Graphics:Images/index2_gr_43.gif]
[Graphics:Images/index2_gr_44.gif]
[Graphics:Images/index2_gr_45.gif]


Plotting Your Function

The following example details how to plot the output that is returned from polyfunction. In this example, the first plot is colored blue and the second red, using the PlotStyle option.

[Graphics:Images/index2_gr_46.gif]

[Graphics:Images/index2_gr_47.gif]


Evaluating a Function at Numerous Points

You can create a table of values for your function. This example evaluates the polyfunction for each of the values of [Graphics:Images/index2_gr_49.gif].

[Graphics:Images/index2_gr_50.gif]
[Graphics:Images/index2_gr_51.gif]

You can also evaluate your function at an arbitrary set of values. For example, suppose you wish to evaluate polyfunction at the following list of values.

[Graphics:Images/index2_gr_52.gif]
[Graphics:Images/index2_gr_53.gif]

Using the Map function, you can apply polyfunction to each of the values in valuelist.

[Graphics:Images/index2_gr_54.gif]
[Graphics:Images/index2_gr_55.gif]


Iterating Functions

Oftentimes, you have a need to iterate a function; that is, evaluate the function repeatedly, using each output for the succeeding input. For example, you can create a function entitled newtonfunction, which is essentially a recreation of Newton's method.

[Graphics:Images/index2_gr_56.gif]
[Graphics:Images/index2_gr_57.gif]

Nest and NestList allow you to repeatedly apply the same function to the output of the function.

Now you can repeatedly apply newtonfunction to the output from the previous recursion. Beginning with x = 2 in this case, NestList will apply newtonfunction to its output as specified.

[Graphics:Images/index2_gr_59.gif]
[Graphics:Images/index2_gr_60.gif]

Unlike NestList, Nest does not return the starting point and subsequent iterations as it works through newtonfunction. Although Nest arrives at the same result, it returns only the final result and not the intermediate steps.

[Graphics:Images/index2_gr_61.gif]
[Graphics:Images/index2_gr_62.gif]


 © 2008 Wolfram Research, Inc.  Terms of Use  Privacy Policy | [ja] |
Sign up for our newsletter: