You are on page 1of 11

Learning MATLAB: tips & examples (PG-13)

FranciscoJavier Sayas
Version of 6th March 2010
This is a compilation of programming hints and examples about how to use and program MAT-
LAB, with a mind on numerical methods. At present time, this is work in progress, so its
important to know which version of this document you are dealing with. There will not be
detailed explanations of the examples: I will specically concentrate on where I think you might
have trouble or you might be learning something new.
Before even trying to use this document, be sure that you know:
how to deal with matrices and vectors in MATLAB, at least at a very basic level,
how to edit a document,
what is an mfunction (or mle) and how it is used,
what is the dierence between a script and a function,
how to use the most elementary graphing capabilities of MATLAB (such as plot and the
like),
how to use the MATLAB help (the interactive help is usually enough).
I have adapted and translated part of this document from the classnotes Un curso de MATLAB
(A course of MATLAB), in Spanish, developed by some members of the FMI Group in Zaragoza
(Spain) under my coordination.
1
Contents
1 Functions 3
1.1 Some examples of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Vectorized functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3 Inline functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.4 Anonymous functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.5 Functions as arguments of other functions . . . . . . . . . . . . . . . . . . . . . . 7
1.6 Vectorization of constant and piecewise dened functions . . . . . . . . . . . . . 8
2
Chapter 1
Functions
1.1 Some examples of functions
Warning. MATLAB does not have any problem distinguishing capital and small letters, so in
principle you can create two dierent functions called nameoff and nameofF. However, take into account
that Windows has trouble with that, so as a matter of principle, avoid names with the same characters
whose only dierence is the character type.
The function example is to be kept in a le called example.m. If the name of the le does not
coincide with the name of the function, the name that MATLAB will understand is the
name of the le. You can use any function you create in the folder where you are working,
plus functions in other folders that you add to the path where MATLAB looks for functions.
example.m
function [z,t]=example(x,y)
% This is where you write the basic help commands that will appear
% when you type help example
z=x-y;
t=x+y; % write semicolons to avoid showing intermediate computations
return % the return command is optional, but recommended
We are now ready to use the function. If you do not give output arguments, you will get only
the value of the rst output argument.
>> help example % trying the help command
This is where you write the basic help commands that will appear
when you type help example
>> example(2,3)
3
ans =
-1 % This is the value of the first output argument
>> [a,b]=example(2,3)
a =
-1
b =
5
1.2 Vectorized functions
A scalar function of one variable is vectorized when if the input is an array, the output is an
array of the same size. For scalar functions of several variables, vectorization assumes that in
the input variables we give arrays of the same size and we expect as output an array of the given
size.
For construction of vectorized functions, you can count on the many capabilities of MATLAB
in this direction:
The symbols for sum and subtraction are vectorized,
Addition of scalars, change of sign and multiplication by scalars are vectorized.
For elementbyelement multiplication and division use the symbols
.* and ./
respectively.
The symbol .^ is used to get the elementbyelement power of a matrix by a number.
Most common mathematical functions are vectorized. For instance: abs, sin, cos, exp,
log,... are vectorized. Be careful, for instance, with the meaning of exp(A): it does not
compute e
A
in the mathematical sense of the word (meaningful for square matrices).
>> 1 + [2 3 5]
ans =
3 4 6
>> 2 * [3 ; 7]
ans =
6
14
>> [2 3;-1 2].^4
ans =
16 81
1 16
>> [3 5;1 2].*[2 1;-1 4] % element by element product
4
ans =
6 5
-1 8
>> [3 5;1 2]*[2 1;-1 4] % matrix product
ans =
1 23
0 9
If you do not how to vectorize an expression, you can ask MATLAB to do it for you, using the
command vectorize.
>> vectorize(x^2+sin(x)*y)
ans =
x.^2+sin(x).*y
1.3 Inline functions
You can create simple functions in a very straightforward way by using inline. This can be
done if you have the symbolic package. It is highly recommendable to give the names of the
variables, even if they are not needed. If you do not give the name of the variables, you risk them
being in a dierent order than what you wanted: MATLAB is going to opt for the alphabetical
order, unless you specify the order of the variables by writing them explicitly in the command
to create the function.
>> f=inline(x.^2+2*x,x) % expression + names of variables
f =
Inline function:
f(x) = x.^2+2*x
>> f(3)
ans =
15
>> f([3 7]) % We were careful to have the function vectorized
ans =
15 63
>> f=inline(x^2+2*x*y,x,y) % Function of two variables
f =
Inline function:
f(x,y) = x^2+2*x*y
>> f=vectorize(f) % We let MATLAB vectorize f (works only with inline!)
f =
Inline function:
5
f(x,y) = x.^2+2.*x.*y
>> f([1 3 2.1],[2 -1 4]) % Using vectorization
ans =
5.0000 3.0000 21.2100
>> [f(1,2), f(3,-1), f(2.1, 4)] % = not using it
ans =
5.0000 3.0000 21.2100
>> f=inline(x.^2+2*x.*a) % Not giving the variables
f =
Inline function:
f(a,x) = x.^2+2*x.*a
>> f=inline(x.^2+2*x.*a,x,a) % Giving the variables
f =
Inline function:
f(x,a) = x.^2+2*x.*a
1.4 Anonymous functions
There is a third way of dening functions in the MATLAB workspace. The syntax is not
very attractive, but they are very convenient and, actually, they are faster to evaluate than
inline function. This type of function is known as anonymous functions. Here are some simple
examples:
>> f =@(x) x.^2+2; % A vectorized function of one variable
>> f([1 2 3])
ans =
3 6 11
>> g=@(x,y) x.^2+y.^2; % A vectorized function of two variables
>> h = @(t,y) [y(1)+t;y(1)+y(2)-t];
% This one is vector valued and one of the variables is a vector
>> h(0.1,[2 3])
ans =
2.1000
4.9000
>> f=inline(x.^2+y.^2); % The same function as inline function
>> whos f g
Name Size Bytes Class Attributes
f 1x1 882 inline
g 1x1 16 function_handle
6
As you can see, inline and anonymous functions have dierent types. The anonymous type will
give you faster results, as far as I know. The rules for general functions (possibility of recursion
and nested denition), apply. Wait for the following section to have functions that have other
functions as arguments.
1.5 Functions as arguments of other functions
The simplest way to use a function as an argument of another function is to send its handle
1
.
Here is an example of a function that simply averages another function in two given points.
average.m
function y=average(f,a,b)
% function y=average(f,a,b)
% Input: f : handle of function
% a : 1st point
% b : 2nd point
% Output: 0.5*(f(a)+f(b))
y=0.5*(f(a)+f(b));
return
We now use the function average with inline functions and with MATLABs own functions.
The variable where we keep an inline function is its own handle. The handle of an anonymous
function is its own name. The handle of a MATLAB function is dierent. You have to add the
symbol @ before the name of the function: for instance, the handle of sin is @sin.
>> h=inline(x.^2+1,x)
h =
Inline function:
h(x) = x.^2+1
>> average(h,2,3)
ans =
7.5000
>> average(h,[2 4],[3 5]) % using that h is vectorized
ans =
7.5000 21.5000
>> average(@exp,0,1)
ans =
1.8591 % = (1+exp(1))/2
1
There is another way, sending the name and evaluating then the function using feval, which makes everything
look more complicated. For relatively simple problems it is better to use the handle.
7
We nally create a function with an mle. Its handle is its name preceded by @.
g.m
function y=g(x)
% This function is vector valued
y=[x.^2+2*x-1; ...
sin(x)];
return
Note how average does not care that g is vector valued.
>> average(@g,2,3)
ans =
10.5000
0.5252
The same process can be done with anonymous functions, for instance.
>> average = @(f,a,b) 0.5*(f(a)+f(b));
>> psi = @(t) t.^2-2*t;
>> average(psi,[0 1 2],[1 2 3])
ans =
-0.5000 -0.5000 1.5000
1.6 Vectorization of constant and piecewise dened functions
To vectorize a constant function you need to do some additional work. To dene, for
instance, the constant function f 3, the cheapest form (shown with an inline structure; the
process is similar for mle dened functions) is
>> f=inline(3*ones(size(x)),x);
>> f([2 3 4; 4 3 2])
ans =
3 3 3
3 3 3
8
Another option, which results in a slightly more computationally expensive function would be
performing the dirty trick f(x) = 3 + 0 x, that forces f to have the same size as x.
>> f=inline(3+0*x,x);
>> f([2 3 4; 4 3 2])
ans =
3 3 3
3 3 3
To vectorize a function that is dened in a piecewise fashion there are several ways. We are
rst going to dene
(t) =

t + 1, if t 1
t + 3, if 1 < t 2,
7
1
2
t
2
, if t > 2.
The key is the possibility of dening characteristic/indicator functions using boolean expressions.
We are actually going to program the function
(t) = (t + 1)1
t1
+ (t + 3)1
1<t2
+ (7
1
2
t
2
)1
t>2
.
Be very careful though to avoid having a point satisfying two sets of conditions. You might end
up adding values. Note that changing the last indicator function to 1
t2
will give you a dierent
value in t = 2. The programming trick can be used with mle, inline and anonymous functions:
>> psi=inline((t<=1).*(1+t) + (1<t & t<=2).*(t+3) + (t>2).*(-0.5*t.^2+7));
>> psi([0 1 2 3])
ans =
1.0000 2.0000 5.0000 2.5000
>> fplot(psi,[0,4]) % you can use fplot (see the result below)
Lets do this other one now, to see a possible unexpected diculty:
u(x, y) =


1 x
2
y
2
, if x
2
+ y
2
1,
0, if x
2
+ y
2
> 1.
The expression in the case x
2
+ y
2
1 is going to give you an error if you try evaluation
with x
2
+ y
2
> 1, but the kind of program we have done before actually evaluates each of the
possibilities in all the points and only after that cuts with the indicator functions. Therefore,
we are going to program this function

|1 x
2
y
2
| 1
x
2
+y
2
1
.
9
>> u = @(x,y) (x.^2+y.^2 <= 1).*sqrt(abs(1-x.^2-y.^2));
>> [x,y]=meshgrid(linspace(-1.5,1.5,100));
>> surf(x,y,u(x,y)), shading flat, axis equal (see the result below)
Note that this kind of very elementary vectorization of piecewise dened functions is relatively
expensive for the reason given above: each expression is evaluated everywhere and only then
multiplied by the indicator function that chooses the piece or not. However, this is a very simple
option.
There is a dierent way, that saves the time of computing a function where is not going to be
used and also the inconvenience of having to extend the expression outside its natural domain of
denition. This kind of solution is much more dicult to dene as inline or anonymous function.
u.m
function z=u(x,y)
z=zeros(size(x));
c1=x.^2+y.^2<=1; % we find where the condition is satisfied
z(c1)=sqrt(1-x(c1).^2-y(c1).^2); % we evaluate only there
end
0 0.5 1 1.5 2 2.5 3 3.5 4
1
0
1
2
3
4
5
1.5
1
0.5
0
0.5
1
1.5
1.5
1
0.5
0
0.5
1
1.5
0
0.2
0.4
0.6
0.8
Figure 1.1: The two gures produced in Section 1.6
10

You might also like