MAT LAB Built-in functions


Built-in functions

There are numerous built-in functions (i.e. commands) in MATLAB. We will mention a few of them in this section by separating them into categories.

Scalar Functions

Certain MATLAB functions are essentially used on scalars, but operate element-wise when applied to a matrix (or vector). They are summarized in the table below.

sin            trigonometric sine
cos           trigonometric cosine
tan           trigonometric tangent
asin          trigonometric inverse sine (arcsine)
acos         trigonometric inverse cosine (arccosine)
atan          trigonometric inverse tangent (arctangent)
exp          exponential
log           natural logarithm
abs          absolute value
sqrt          square root
rem          remainder
round       round towards nearest integer
floor         round towards negative infinity
ceil           round towards positive infinity


Even though we will illustrate some of the above commands in what follows, it is strongly recommended to get help on all of them to find out exactly how they are used. The trigonometric functions take as input radians. Since MATLAB uses pi for the number

π = 3.1415…
» sin(pi/2)
ans =
1
» cos(pi/2)
ans =
6.1230e-017

The sine of π/2 is indeed 1 but we expected the cosine of π/2 to be 0. Well, remember that MATLAB is a numerical package and the answer we got (in scientific notation) is very close to
0 ( 6.1230e-017 = 6.1230×10 –17 ≈ 0).

Since the exp and log commands are straight forward to use, let us illustrate some of the other commands. The rem command gives the remainder of a division. So the remainder of 12 divided by 4 is zero

» rem(12,4)
ans =
0
and the remainder of 12 divided by 5 is 2.

» rem(12,5)
ans =
2

The floor, ceil and round commands are illustrated below.

» floor(1.4)
ans =
1
» ceil(1.4)
ans =
2

» round(1.4)
ans =
1

Keep in mind that all of the above commands can be used on vectors with the operation taking place element-wise. For example, if x = [0, 0.1, 0.2, . . ., 0.9, 1], then y = exp(x) will produce another vector y , of the same length as x, whose entries are given by y = [e0, e0.1, e0.2, . . ., e1].

» x = [0:0.1:1]
x =

Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000
Columns 8 through 11
0.7000 0.8000 0.9000 1.0000

» y = exp(x)
y =

Columns 1 through 7
1.0000 1.1052 1.2214 1.3499 1.4918 1.6487 1.8221
Columns 8 through 11
2.0138 2.2255 2.4596 2.7183

This is extremely useful when plotting data. See Section 2.4 ahead for more details on plotting. Also, note that MATLAB displayed the results as 1-by-11 matrices (i.e. row vectors of length 11). Since there was not enough space on one line for the vectors to be displayed, MATLAB reports the column numbers.

Vector Functions

Other MATLAB functions operate essentially on vectors returning a scalar value. Some of these functions are given in the table below.

max                 largest component
min                  smallest component
length              length of a vector

sort                 sort in ascending order
sum                 sum of elements
prod                 product of elements
median            median value
mean              mean value
std                  standard deviation

Once again, it is strongly suggested to get help on all the above commands. Some are illustrated below.
Let z be the following row vector.

» z = [0.9347,0.3835,0.5194,0.8310]
z =
0.9347 0.3835 0.5194 0.8310
Then

» max(z)
ans =
0.9347

» min(z)
ans =
0.3835

» sort(z)
ans =
0.3835 0.5194 0.8310 0.9347

» sum(z)
ans =
2.6686

» mean(z)
ans =
0.6671

The above (vector) commands can also be applied to a matrix. In this case, they act in a column by- column fashion to produce a row vector containing the results of their application to each column. The example below illustrates the use of the above (vector) commands on matrices Suppose we wanted to find the maximum element in the following matrix.


» M = [
0.7012,0.2625,0.3282
0.9103,0.0475,0.6326
0.7622,0.7361,0.7564];

If we used the max command on M, we will get the row in which the maximum element lies (remember the vector functions act on matrices in a column-by-column fashion).

» max(M)
ans =
0.9103 0.7361 0.7564

To isolate the largest element, we must use the max command on the above row vector. Taking advantage of the fact that MATLAB assigns the variable name ans to the answer we obtained, we can simply type

» max(ans)
ans =
0.9103

The two steps above can be combined into one in the following.

» max(max(M))
ans =
0.9103

Combining MATLAB commands can be very useful when programming complex algorithms where we do not wish to see or access intermediate results. More on this, and other programming features of MATLAB in Section  ahead.

Matrix Functions

Much of MATLAB’s power comes from its matrix functions. These can be further separated into two sub-categories. The first one consists of convenient matrix building functions, some of which are given in the table below.

eye          identity matrix
zeros       matrix of zeros
ones        matrix of ones
diag        extract diagonal of a matrix or create diagonal matrices
triu          upper triangular part of a matrix
tril           lower triangular part of a matrix
rand        randomly generated matrix


Make sure you ask for help on all the above commands. To create the identity matrix of size 4 (i.e. a square 4-by-4 matrix with ones on the main diagonal  and zeros everywhere else) we use the command eye.

» eye(4,4)
ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

The numbers in parenthesis indicates the size of the matrix. When creating square matrices, we can specify only one input referring to size of the matrix. For example, we could have obtained the above identity matrix by simply typing eye(4). The same is true for the matrix building functions below. Similarly, the command zeros creates a matrix of zeros and the command ones creates a matrix of ones.

» zeros(2,3)
ans =
0 0 0
0 0 0

» ones(2)
ans =
1 1
1 1

We can create a randomly generated matrix using the rand command. (The entries will be uniformly distributed between 0 and 1.)

» C = rand(5,4)
C =
0.2190 0.3835 0.5297 0.4175
0.0470 0.5194 0.6711 0.6868
0.6789 0.8310 0.0077 0.5890
0.6793 0.0346 0.3834 0.9304
0.9347 0.0535 0.0668 0.8462

The commands triu and tril, extract the upper and lower part of a matrix, respectively. Let us try them on the matrix C defined above.

triu(C)

ans =
0.2190 0.3835 0.5297 0.4175
0 0.5194 0.6711 0.6868
0 0 0.0077 0.5890
0 0 0 0.9304
0 0 0 0

» tril(C)
ans =
0.2190 0 0 0
0.0470 0.5194 0 0
0.6789 0.8310 0.0077 0
0.6793 0.0346 0.3834 0.9304
0.9347 0.0535 0.0668 0.8

Once the extraction took place, the “empty” positions in the new matrices are automatically filed with zeros.
As mentioned earlier, the command diag has two uses. The first use is to extract a diagonal of a matrix, e.g. the main diagonal. Suppose D is the matrix given below. Then, diag(D) produces a column vector, whose components are the elements of D that lie on its main diagonal.

» D = [
0.9092 0.5045 0.9866
0.0606 0.5163 0.4940
0.9047,0.3190,0.2661];
» diag(D)
ans =
0.9092
0.5163
0.2661

The second use is to create diagonal matrices. For example,

» diag([0.9092;0.5163;0.2661])
ans =
0.9092 0 0
0 0.5163 0
0 0 0.2661


creates a diagonal matrix whose non-zero entries are specified by the vector given as input. (A short cut to the above construction is diag(diag(D)) ). This command is not restricted to the main diagonal of a matrix; it works on off diagonals as well. See help diag for more information. Let us now summarize some of the commands in the second sub-category of matrix functions.

size     size of a matrix
det      determinant of a square matrix
inv       inverse of a matrix
rank    rank of a matrix
rref     reduced row echelon form
eig      eigenvalues and eigenvectors
poly    characteristic polynomial
norm   norm of matrix (1-norm, 2-norm, ∞ -norm)
cond   condition number in the 2-norm
lu        LU  factorization
qr       QR factorization
chol     Cholesky decomposition
svd      singular value decomposition

Don’t forget to get help on the above commands. To illustrate a few of them, define the following matrix.

» A = [9,7,0;0,8,6;7,1,-6]
A =
9 7 0
0 8 6
7 1 -6

» size(A)
ans =
3 3

» det(A)
ans =
192

Since the determinant is not zero, the matrix is invertible.

» inv(A)
ans =
0.2812 -0.2187 -0.2187
-0.2187 0.2812 0.2812
0.2917 -0.2083 -0.3750


We can check our result by verifying that AA–1 = I and A–1A = I .

» A*inv(A)
ans =
1.0000 0.0000 0.0000
0.0000 1.0000 0.0000
0.0000 0.0000 1.0000

» inv(A)*A
ans =
1.0000 0.0000 0
0.0000 1.0000 0
0.0000 0 1.0000

Let us comment on why MATLAB uses both 0’s and 0.0000’s in the answer above. Recall that we are dealing with a numerical package that uses numerical algorithms to perform the operations we ask for. Hence, the use of floating point (vs. exact) arithmetic causes the “discrepancy” in the results. From a practical point of view, 0 and 0.0000 are the same. The eigenvalues and eigenvectors of A (i.e. the numbers λ and vectors x that satisfy Ax = λx ) can be obtained through the eig command.

» eig(A)
ans =
12.6462
3.1594
-4.8055

produces a column vector with the eigenvalues and

» [X,D]=eig(A)
X =
-0.8351 -0.6821 0.2103
-0.4350 0.5691 -0.4148
-0.3368 -0.4592 0.8853
D =
12.6462 0 0
0 3.1594 0
0 0 -4.8055

produces a diagonal matrix D with the eigenvalues on the main diagonal, and a full matrix X whose columns are the corresponding eigenvectors.









Matlab Basics

MATLAB BASICS

 The basic features

Let us start with something simple, like defining a row vector with components the numbers 1, 2, 3, 4, 5 and assigning it a variable name, say x.
» x = [1 2 3 4 5]
x =
1 2 3 4 5

Note that we used the equal sign for assigning the variable name x to the vector, brackets to enclose its entries and spaces to separate them. (Just like you would using the linear algebra notation). We could have used commas ( , ) instead of spaces to separate the entries, or even a combination of the two. The use of either spaces or commas is essential! 
       To create a column vector (MATLAB distinguishes between row and column vectors, as it should) we can either use semicolons ( ; ) to separate the entries, or first define a row vector and take its transpose to obtain a column vector. Let us demonstrate this by defining a column vector y with entries 6, 7, 8, 9, 10 using both techniques.

» y = [6;7;8;9;10]
y =
6
7
8
9
10

» y = [6,7,8,9,10]
y =
6 7 8 9 10

» y'
ans =
6
7
8
9
10

Let us make a few comments. First, note that to take the transpose of a vector (or a matrix for that matter) we use the single quote ( ' ). Also note that MATLAB repeats (after it processes) what we typed in. Sometimes, however, we might not wish to “see” the output of a specific command. We can suppress the output by using a semicolon ( ; ) at the end of the command line. Finally, keep in mind that MATLAB automatically assigns the variable name ans to anything that has not been assigned a name. In the example above, this means that a new variable has been created with the column vector entries as its value. The variable ans, however, gets recycled and every time we type in a command without assigning a variable, ans gets that value. It is good practice to keep track of what variables are defined and occupy our work space. Due to the fact that this can be cumbersome, MATLAB can do it for us. The command whos gives all sorts of information on what variables are active.

» whos Name Size Elements Bytes Density Complex
ans 5 by 1 5 40 Full No
x 1 by 5 5 40 Full No
y 1 by 5 5 40 Full No
Grand total is 15 elements using 120 bytes

A similar command, called who, only provides the names of the variables that are active.
» who
Your variables are:
ans x y

If we no longer need a particular variable we can “erase” it from memory using the command clear variable_name. Let us clear the variable ans and check that we indeed did so.
» clear ans
» who
Your variables are:
x y

The command clear used by itself, “erases” all the variables from the memory. Be careful, as this is not reversible and you do not have a second chance to change your mind. You may exit the program using the quit command. When doing so, all variables are lost. However, invoking the command save filename before exiting, causes all variables to be written to a binary file called filename.mat. When we start MATLAB again, we may retrieve the information in this file with the command load filename. We can also create an ascii (text) file containing the entire MATLAB session if we use the command diary filename at the beginning and at the end of our session. This will create a text file called filename (with no extension) that can be edited with any text editor, printed out etc. This file will include everything we typed into MATLAB during the session (including error messages but excluding plots). We could also use the command save filename at the end of our session to create the binary file described above as well as the text file that includes our work. One last command to mention before we start learning some more interesting things about MATLAB, is the help command. This provides help for any existing MATLAB command. Let us try this command on the command who.

» help who
WHO List current variables.
WHO lists the variables in the current workspace.
WHOS lists more information about each variable.
WHO GLOBAL and WHOS GLOBAL list the variables in the global work space. Try using the command help on itself!
On a PC, help is also available from the Window Menus. Sometimes it is easier to look up a
command from the list provided there, instead of using the command line help.

Vectors and matrices

We have already seen how to define a vector and assign a variable name to it. Often it is useful to define vectors (and matrices) that contain equally spaced entries. This can be done by specifying the first entry, an increment, and the last entry. MATLAB will automatically figure out how many entries you need and their values. For example, to create a vector whose entries

are 0, 1, 2, 3, …, 7, 8, you can type
» u = [0:8]
u =
0 1 2 3 4 5 6 7 8
Here we specified the first entry 0 and the last entry 8, separated by a colon ( : ). MATLAB automatically filled-in the (omitted) entries using the (default) increment 1. You could also specify an increment as is done in the next example.

To obtain a vector whose entries are 0, 2, 4, 6, and 8, you can type in the following line:
» v = [0:2:8]
v =
0 2 4 6 8
Here we specified the first entry 0, the increment value 2, and the last entry 8. The two colons ( : ) “tell” MATLAB to fill in the (omitted) entries using the specified increment value. MATLAB will allow you to look at specific parts of the vector. If you want, for example, to only look at the first 3 entries in the vector v, you can use the same notation you used to create the vector:

» v(1:3)
ans =
0 2 4
Note that we used parentheses, instead of brackets, to refer to the entries of the vector. Since we omitted the increment value, MATLAB automatically assumes that the increment is 1. The following command lists the first 4 entries of the vector v, using the increment value 2 :
» v(1:2:4)
ans =
0 4

Defining a matrix is similar to defining a vector. To define a matrix A, you can treat it like a column of row vectors. That is, you enter each row of the matrix as a row vector (remember to separate the entries either by commas or spaces) and you separate the rows by semicolons ( ; ).
» A = [1 2 3; 3 4 5; 6 7 8]
A =
1 2 3
3 4 5
6 7 8
We can avoid separating each row with a semicolon if we use a carriage return instead. In other words, we could have defined A as follows
» A = [
1 2 3
3 4 5
6 7 8]
A =
1 2 3
3 4 5
6 7 8
which is perhaps closer to the way we would have defined A by hand using the linear algebra notation.
You can refer to a particular entry in a matrix by using parentheses. For example, the number 5 lies in the 2nd row, 3rd column of A, thus
» A(2,3)
ans =
5
The order of rows and columns follows the convention adopted in the linear algebra notation. This means that A(2,3) refers to the number 5 in the above example and A(3,2) refers to the number 7, which is in the 3rd row, 2nd column. Note MATLAB’s response when we ask for the entry in the 4th row, 1st column.

» A(4,1)
??? Index exceeds matrix dimensions.
As expected, we get an error message. Since A is a 3-by-3 matrix, there is no 4th row and MATLAB realizes that. The error messages that we get from MATLAB can be quite informative when trying to find out what went wrong. In this case MATLAB told us exactly what the problem was. We can “extract” submatrices using a similar notation as above. For example to obtain the submatrix that consists of the first two rows and last two columns of A we type
» A(1:2,2:3)
ans =
2 3
4 5
We could even extract an entire row or column of a matrix, using the colon ( : ) as follows. Suppose we want to get the 2nd column of A. We basically want the elements [A(1,2) A(2,2) A(3,2)]. We type
» A(:,2)
ans =
2
4
7
where the colon was used to tell MATLAB that all the rows are to be used. The same can be
done when we want to extract an entire row, say the 3rd one.
» A(3,:)
ans =
6 7 8
Define now another matrix B, and two vectors s and t that will be used in what follows.
» B = [
-1 3 10
-9 5 25
0 14 2]
B =
-1 3 10
-9 5 25
0 14 2
» s = [-1 8 5]
s =
-1 8 5
» t = [7;0;11]
t =
7
0
11
The real power of MATLAB is the ease in which you can manipulate your vectors and matrices. For example, to subtract 1 from every entry in the matrix A we type
» A-1
ans =
0 1 2
2 3 4
5 6 7
It is just as easy to add (or subtract) two compatible matrices (i.e. matrices of the same size).
» A+B
ans =
0 5 13
-6 9 30
6 21 10
The same is true for vectors.
» s-t
??? Error using ==> -
Matrix dimensions must agree. This error was expected, since s has size 1-by-3 and t has size 3-by-1. We will not get an error if
we type
» s-t'
ans =
-8 8 -6
since by taking the transpose of t we make the two vectors compatible. We must be equally careful when using multiplication.
» B*s
??? Error using ==> *
Inner matrix dimensions must agree.
» B*t
ans =
103
212
22
Another important operation that MATLAB can perform with ease is “matrix division”. If M is an invertible† square matrix and b is a compatible vector then

x = M\b is the solution of M x = b and
x = b/M is the solution of x M = b.
Let us illustrate the first of the two operations above with M = B and b = t.
» x=B\t
x =
2.4307
0.6801
0.7390
x is the solution of B x = t as can be seen in the multiplication below.
» B*x
ans =
7.0000
0.0000
11.0000
Since x does not consist of integers, it is worth while mentioning here the command format long. MATLAB only displays four digits beyond the decimal point of a real number unless we use the command format long, which tells MATLAB to display more digits.
» format long
» x
x =
2.43071593533487
0.68013856812933
0.73903002309469
On a PC the command format long can also be used through the Window Menus. † Recall that a matrix M ∈ 􀁜n×n is called invertible if Mx=0 ⇒ x=0 ∀x∈􀁜n . There are many times when we want to perform an operation to every entry in a vector or matrix. MATLAB will allow us to do this with “element-wise” operations. For example, suppose you want to multiply each entry in the vector s with itself. In other words,
suppose you want to obtain the vector s2 = [s(1)*s(1), s(2)*s(2), s(3)*s(3)]. The command s*s will not work due to incompatibility. What is needed here is to tell MATLAB to perform the multiplication element-wise. This is done with the symbols ".*". In fact, you can put a period in front of most operators to tell MATLAB that you want the operation to take place on each entry of the vector (or matrix).
» s*s
??? Error using ==> *
Inner matrix dimensions must agree.
» s.*s
ans =
1 64 25
The symbol " .^ " can also be used since we are after all raising s to a power. (The period is needed here as well.)
» s.^2
ans =
1 64 25

The table below summarizes the operators that are available in MATLAB.

+ addition
- subtraction
* multiplication
^ power
' transpose
\ left division
/ right division

Remember that the multiplication, power and division operators can be used in conjunction with a period to specify an element-wise operation.