Defining a function in Mathematica

In summary, a function in Mathematica is a block of code that takes in inputs and produces an output. It can be defined using the Function or := operators, with the syntax functionName[input1, input2,...]:= expression. The Function operator creates an anonymous function while := creates a named function. A function in Mathematica can have multiple outputs, defined using the Return or List operator. To call a function, use its name followed by the input values in square brackets, and specify which output to use with the Part operator if necessary.
  • #1
nikolafmf
114
0
Hello,

I know that in Mathematica one can define a function as follows:

f[x_]:=x^2.

The problem is, I get a polynomial from a for loop as an expression p=a*x^n+b*x^(n-1)+... Now I want to evaluate the polynomial at a specific point. I tried to define a function from the polynomial as follows:

f[x_]:=p

and to evaluate

f[2]

which gives me just the polynomial, not it's value at 2.

How can I evaluate this?


Nikola
 
Physics news on Phys.org
  • #2
I have already found out:

f = Function[k, p /. x -> k]

:D
 

FAQ: Defining a function in Mathematica

What is a function in Mathematica?

A function in Mathematica is a block of code that takes in input values and produces an output value. It can be used to perform calculations, manipulate data, or create visualizations.

How do you define a function in Mathematica?

To define a function in Mathematica, you can use the Function or := operators. The syntax is functionName[input1, input2,...]:= expression. This creates a function with the given name and inputs, and defines the output value using the expression.

What is the difference between defining a function with Function and :=?

The Function operator creates an anonymous function, meaning it does not have a specific name. It is useful for creating temporary or one-time use functions. The := operator, also known as the SetDelayed operator, creates a named function that can be used repeatedly.

Can a function in Mathematica have multiple outputs?

Yes, a function in Mathematica can have multiple outputs. You can use the Return operator to specify multiple values to be returned from a function. Alternatively, you can use the List operator to return a list of values.

How do you call a defined function in Mathematica?

To call a function in Mathematica, you simply use its name followed by the input values in square brackets, like functionName[input1, input2,...]. If the function has multiple outputs, you can use the Part operator to specify which output you want to use.

Similar threads

Replies
1
Views
733
Replies
4
Views
1K
Replies
19
Views
1K
Replies
2
Views
464
Replies
5
Views
2K
Replies
3
Views
2K
Replies
4
Views
1K
Back
Top