If we wish to deal with a function that is a combination of the built-in functions, Matlab has a couple of ways for the user to define functions. One that we will use a lot is the anonymous function, which is a way to define a function in the command window. The following is a typical anonymous function:
>> f = @(x) 2*x.^2 - 3*x + 1
This produces the function
\(f(x) = 2 x^{2} -3x+1\text{.}\) To obtain a single value of this function enter
Just as for built-in functions, the function
\(f\) as we defined it can operate not only on single numbers but on vectors. Try the following:
>> x = -2:.2:2
>> y = f(x)
This is an example of vectorization, i.e. putting several numbers into a vector and treating the vector all at once, rather than one component at a time, and is one of the strengths of MATLAB. The reason
\(f(x)\) works when
\(x\) is a vector is because we represented
\(x^{2}\) by
x.^2. The
. turns the exponent operator
^ into entry-wise exponentiation, so that
[-2 -1.8 -1.6].^2 means
\([(-2)^{2}, (-1.8)^{2}, (-1.6)^{2}]\) and yields
[4 3.24 2.56]. In contrast,
[-2 -1.8 -1.6]^2 means the matrix product
\([-2, -1.8,-1.6][-2, -1.8,-1.6]\) and yields only an error. The
. is needed in
.^,
.*, and
./. It is not needed when you
* or
/ by a scalar or for
+.
The results can be plotted using the
plot command, just as for data:
Notice that before plotting the function, we in effect converted it into data. Plotting on any machine always requires this step.