An Introduction To MATLAB: 10.3.1 Creating Matrices
An Introduction To MATLAB: 10.3.1 Creating Matrices
An Introduction To MATLAB: 10.3.1 Creating Matrices
Chapter 10
An Introduction to MATLAB
10.1 Introduction
MATLAB is a modern software package for technical computing. It proved to be a powerful
tool for scientific and engineering numerical computation, visualization, and programming. It
is able to solve efficiently complex numerical problems arising in different areas of science and
engineering. The name MATLAB is derived from MATrix LABoratory.
This tutorial is designed to assist you in learning to use MATLAB. No history of using MAT-
LAB is required. A preliminary knowledge of elementary linear algebra concepts is assumed. A
background in programming principles is desirable for understanding the programming capabili-
ties of the package. For additional information on functions, commands, and examples the reader
is encouraged to use the on-line help facility and Reference/User’s guide attached to the software
and available from http://www.mathworks.com.
(a) >> A = [1 2 3 ; 4 4 3 ; 2 2 4]
133
134 CHAPTER 10. AN INTRODUCTION TO MATLAB
(b) >> A = [1 2 3
4 4 3
2 2 4]
(c) >> A = [1, 2, 3; 4 4 3
2 2 4]
A =
1 2 3
4 4 3
2 2 4
In the above, A is called variable, the set of symbols after equal sign is called expression; the
varible and expression, together with the equal sign form statement.
In general, a statement can consist of a (previously defined) variable only or of an expression
only. In the last case (when a statement is an expression), the result of the expression is assigned
to a default variable ans (a short for answer).
Example 10.2.
>> [4 5 6 7]
ans =
4 5 6 7
In the case when a statement consists of a variable only, MATLAB returns the value of this
variable (or an error message, if the variable was not previously defined). If a statement is
finished with a semicolon (;), the output is suppressed, but the operation determined by this
statement is completed.
Example 10.3.
B =
1 2 3
4 5 6
>> b
??? Undefined function or variable ’b’.
The last example also demonstrates that MATLAB is case-sensitive in the names of variables
(functions, commands), i.e. variable B is not the same as b.
10.3. MATRIX BASICS 135
>> B = [1 1; 2 1]
>> B = [1 1 1; 2 2 3]
• if 1 ≤ i ≤ m and 1 ≤ j ≤ n then the element in the i-th row and the j-th column of B
takes value k, and the rest of the matrix is unchanged;
• if i ≥ m + 1 or j ≥ n + 1 then the size of the matrix is increased to fit B(i, j). All the new
components (except B(i, j)) which appeared as a result of the size increasing are set equal
to zero.
Example 10.5.
>> B=[1 2
2 1];
>> B(1,1)=5
B =
5 2
2 1
>> B(3,4)=8
B =
5 2 0 0
2 1 0 0
0 0 0 8
Given a vector c, a single subscript c(i) represents i-th element of the vector. If applied to an
m × n - matrix B, a single subscript B(i) refers to the i-th element of the m × n- dimensional
vector formed from the columns of B.
136 CHAPTER 10. AN INTRODUCTION TO MATLAB
Example 10.6.
ans =
ans =
Given a matrix C we can find its size by using the following command:
[m, n] = size(C);
where the variable m is assigned the number of rows of C and the variable n the number of columns.
To find the length of a vector c we can also use function length:
n = length(c)
Example 10.7.
>> c = [2 0 0 1];
>> [m, n] = size(c)
m =
1
n =
4
>> n = length(c)
n =
represents a vector
[a, a + h, a + 2h, . . . , a + kh].
In the above k is the largest integer, for which a + kh is in the interval [min{a, b}, max{a, b}].
Example 10.8.
>> v = 1:2:10
v =
1 3 5 7 9
>> u=10:-3:-3
u =
10 7 4 1 -2
Example 10.9.
>> 1:8
ans =
1 2 3 4 5 6 7 8
Colons can be used to constract not only vectors, but matrices as well (see the example below).
A subscript expression containing colons refers to a submatrix of a matrix. A colon by itself in
the subscript denotes the entire row or entire column.
Example 10.10. First, we constract a matrix, consisting of three rows each of which is
built using colon notation:
A =
1 2 3 4 5
5 4 3 2 1
2 3 4 5 6
Then we use colons in the subscript to extract a submatrix of A corresponding to its first
two rows and first three columns:
>> A(1:2,1:3)
ans =
1 2 3
5 4 3
138 CHAPTER 10. AN INTRODUCTION TO MATLAB
The submatrix consisting of the first and the third rows of A can be found as follows:
>> A([1,3],:)
ans =
1 2 3 4 5
2 3 4 5 6
>> A(1:2,[1,3])=[1 0; 0 1]
A =
1 2 0 4 5
0 4 1 2 1
2 3 4 5 6
Here a 2 × 2 submatrix of A built from elements of its fist two rows and its first and third
columns, is replaced by the 2 × 2 identity matrix.
+ addition
- subtraction
* multiplication
^ power
’ transpose
\ left division
/ right division
Noted that the dimensions of the matrices used should be chosen in a way that all these operations
are defined, otherwise an error message will occur. To add two matrices A and B we type
E = A + B
and the matrix E is the result of their addition. Respectively, for multiplication
E = A*B
E = A^p
>> v = [1; 2; 3; 4]
>> v = [1 2 3 4]’
(try it).
The matrix division operators are convenient for solving systems of linear equations, where
A\b is nothing else than A−1 b, provided that A is nonsingular.
Example 10.12. Solve a system Ax = b, where A and b are defined below, using left
division:
>> A = [1 4 3; -1 -2 0; 2 2 3]
A =
1 4 3
-1 -2 0
2 2 3
b =
12
-12
8
>> x=A\b
x =
4.0000
4.0000
-2.6667
Having defined the left division, the right division is then introduced as b/A = (A’\b’)’. When
applied to scalars, right and left division differ only in the direction in which the division is made.
Example 10.13.
>> 3/2
ans =
1.5000
>> 3\2
ans =
0.6667
140 CHAPTER 10. AN INTRODUCTION TO MATLAB
If the operators \ / * ^ are preceded by a period, then they perform the same acion but
entry-wise (similarly to addition or subtraction of matrices).
Example 10.14.
>> A=[2 4
3 1];
>> B=[3 4
2 3];
>> A.*B
ans =
6 16
6 3
To create a square matrix, the second argument can be omitted, for example, to generate an
identity matrix An×n we simply type A = eye(n) .
Example 10.15.
>> A = rand(3,2)
A =
0.2190 0.6793
0.0470 0.9347
0.6789 0.3835
>> B=eye(3)+ones(3)
B =
2 1 1
1 2 1
10.4. MANAGING THE WORKSPACE AND THE COMMAND WINDOW 141
1 1 2
>> C=zeros(2,3)
C =
0 0 0
0 0 0
>> clear x
This will save the session to a binary file named filename.mat, which can be later retrieved with
the command
If you omit the filename then the default name given by MATLAB is matlab.mat. However, even
if you save the variables of your workspace in a file, all the output that was generated during a
session has to be re-generated. This is where the diary command is used. More specifically, if
you enter
diary myfile.out
then MATLAB starts saving all the output that is generated in the workspace to the file
myfile.out; the command diary off stops saving the output.
>> a = pi
a =
3.1416
>> b = exp(1)
b =
2.7183
a =
3.14159265358979
>> b
b =
2.71828182845905
10.5. FUNCTIONS 143
Example 10.17.
10.5 Functions
There is a great number and variety of functions that are available in MATLAB. All MATLAB
functions can be subdivided into two types, built-in functions and user-defined functions. In
this section a brief overview of the most important built-in functions is provided, while the
development of user-defined functions is described in Section 10.7.
ex −e−x
Example 10.18. By definition, sinh(x) = 2 . So, for x = 1 we have
ans = ans =
1.1752 1.1752
>> rem(3,2)
ans =
1
144 CHAPTER 10. AN INTRODUCTION TO MATLAB
The function round rounds a number towards the closest integer. It is not the same as the
function fix, which outputs the closest integer towards zero:
ans = ans =
3 2
Functions floor and ceil round a number to the closest non-larger and non-smaller integer,
respectively:
ans = ans =
3 4
ans = ans =
2.7183 3.0000
In all of the presented functions, if the argument x is an m × n matrix, then the function will
be applied to each of its elements and the dimension of the resulting answer will be also a m × n
matrix.
Example 10.19. In this example we take the square roots of absolute values of all elements
of a matrix A, and then round up the resulting elements, assigning the final result to a
matrix D. First, we do this step by step:
>> A = [2 3 -5; 4 2 2; -1 -4 7]
A =
2 3 -5
4 2 2
-1 -4 7
>> B = abs(A)
B =
2 3 5
4 2 2
1 4 7
>> C = sqrt(B)
C =
1.4142 1.7321 2.2361
10.5. FUNCTIONS 145
>> D = ceil(C)
D =
2 2 3
2 2 2
1 2 3
The same can be done in one line, using a superposition of all of the functions applied:
>> D = ceil(sqrt(abs(A)))
D =
2 2 3
2 2 2
1 2 3
>> n=5;
>> x=rand(1,n)
x =
0.3843 0.9427 0.2898 0.4357 0.3234
>> mean(x)
ans =
0.4752
>> sum(x)/n
ans =
0.4752
>> std(x)
ans =
0.2673
>> sqrt((sum(x.^2)-n*mean(x)^2)/(n-1))
ans =
0.2673
Example 10.21. This example shows the (column-wise) action of the function max ap-
plied to a randomly generated matrix A. When applied twice, max(max(A)) outputs the
maximum element in the entire matrix.
>> A=rand(3)
A =
0.8637 0.0562 0.6730
0.8921 0.1458 0.3465
0.0167 0.7216 0.1722
>> max(A)
ans =
0.8921 0.7216 0.6730
>> max(max(A))
ans =
0.8921
10.5. FUNCTIONS 147
n
!1
X p
norm(A, p) = |Ai |p .
i=1
When A is an n×m matrix, then norm(A) is the largest singular value of A while norm(A,’fro’)
is the Frobenius norm of the matrix
1
n X
m 2
X
kAkF = A2ij
i=1 j=1
The function rref(A) provides the reduced row echelon form of matrix A, for example
>> A = [ 3 4 5; 3 -2 1 ]
A =
3 4 5
3 -2 1
>> rref(A)
ans =
1 0 7/9
0 1 2/3
148 CHAPTER 10. AN INTRODUCTION TO MATLAB
An interesting version of this function is the rrefmovie(A) which pauses at each elementary
row operation used to reduced the matrix A to row echelon form.
An n × n system of equations can be written as Ax = b. Expressing A as the product of two
triangular matrices A = LU and letting
y = U x,
we have
Ly = b.
Therefore, we can first solve the last system for y using forward substitution, and knowing y we
can solve the system U x = y for x using back substitution. The matrices L, U are provided by
the function [L,U]=lu(A).
Example 10.22. In this example we find the solution to the linear system
and verify the solution. We use rational approximation output format (format rat).
>> A\b
ans =
138/5
-89/5
-68/5
>> [L,U]=lu(A)
L =
3/5 -2/17 1
2/5 1 0
1 0 0
U =
5 6 2
0 -17/5 21/5
0 0 5/17
>> y=L\b
10.5. FUNCTIONS 149
y =
4
17/5
-4
>> x=U\y
x =
138/5
-89/5
-68/5
The eigenvalues of a matrix and its eigenvectors can be easily found using the function [v,d]=eig(A).
Example 10.23.
A =
2 3 4
4 5 3
1 2 4
>> [v,d]=eig(A)
v =
1898/2653 -605/1154 594/2549
-430/633 -929/1224 -709/900
145/887 -751/1945 3904/6847
d =
130/1987 0 0
0 771/83 0
0 0 1007/612
where the columns of v are the eigenvectors and the diagonal elements of d are the corre-
sponding eigenvalues.
The characteristic polynomial of a matrix A, p(λ) = det(A − λI), can be found using the function
poly(A), which returns a row vector with the coefficients of p(λ). Recall, that the roots of the
characteristic polynomial are the eigenvalues of A.
Example 10.24.
>> A=[1 1; 2 2]
A =
1 1
2 2
>> [v,d]=eig(A)
150 CHAPTER 10. AN INTRODUCTION TO MATLAB
v =
-985/1393 -1292/2889
985/1393 -2584/2889
d =
0 0
0 3
ans =
1 -3 0
p(λ) = λ2 − 3λ
Polynomial Functions
conv → Convolution and polynomial multiplication
deconv → Deconvolution and polynomial division
poly → Polynomial with specified roots
polyder → Polynomial derivative
polyfit → Polynomial curve fitting
polyint → Analytic polynomial integration
polyval → Polynomial evaluation
polyvalm → Matrix polynomial evaluation
roots → Polynomial roots
Mentioned in the previous subsection function poly(v), when applied to a vector v, produces
the vector of the coefficients of the polynomial whose roots are the elements of v. Below we give
examples of using this and other polynomial functions.
Example 10.25. The elements of the vector r=[1 3] are the roots of the polynomial
c(x) = (x − 1)(x − 3) = x2 − 4x + 3 (represented by vector c):
c =
1 -4 3
10.6. PROGRAMMING IN MATLAB 151
p =
1 -6 10 -2 -3
>> h=deconv(p,d)
h =
1 -4 3
>> polyder(p)
ans =
4 -18 20 -2
>> polyval(c,1)
ans =
0
== equals
~= not equals
< less than
> greater than
<= less or equal to
>= greater or equal to
and the value of a relation can be either true (1) or false (0).
152 CHAPTER 10. AN INTRODUCTION TO MATLAB
Example 10.26.
>> v = [2 3 4 5];
>> x = [2 3 6 7];
>> relation = v == x
relation =
1 1 0 0
relation =
0 0 1 1
Here the components of vector relation show if the specified relation is true for the cor-
responding elements of vectors v and x.
for
The general form of a for statement is:
for {variable = expression}
{statements}
end
The columns of the matrix represented by the expression are stored one at a time in the variable,
and the statements are executed. A frequently used form of a for loop is
for i=1:n
{statements}
end
although any other vector, or even matrix can be used instead of 1:n. A for loop in the above
form will repeat the set of statements contained inside exactly n times, each time increasing the
value of i by 1, and then terminate. The following are examples of using for loop in MATLAB.
Example 10.27. This loop sums up all integers between 1 and 10:
>> n = 10;
>> s = 0;
>> for i = 1:n
s = s + i;
end
>> s
s =
55
10.6. PROGRAMMING IN MATLAB 153
Below we show how for loops are used to sum up all the elements of a matrix.
sumA =
120
while
The syntax of while loop is
while {relation}
{statements}
end
The statements contained in this loop are repeated as long as the relation in the first line remains
true. Note that some of the variables participating in this relation should be modified inside the
loop, otherwise it may never terminate.
if
The general form of the if statement is
if {relation}
{statements}
elseif {relation}
{statements}
else
{statements}
end
Example 10.28. To sum the elements above, below and on the diagonal of a matrix A in
three different sums we can use the following sequence of MATLAB statements:
elseif j < i
Lsum = Lsum + A(i, j) ;
else
Dsum = Dsum + A(i, j) ;
end
end
end
where Usum is the sum of the elements of the upper triangular part, Lsum - of the lower
triangular part, and Dsum is the sum of the diagonal elements of A, respectively.
10.6.3 Timing
One of the most important performance measures used to estimate the efficiency of a developed
algorithm, is time required for an algorithm to perform a certain job. In MATLAB, the function
etime in conjunction with the function clock is used to record the elapsed time:
tstart = clock;
{statements}
tend = clock;
totaltime = etime(tend,tstart);
and totaltime will be the time needed for the program to execute the statements.
10.7 M-files
An M-file is a MATLAB-executable file that consists of a sequence of statements and commands.
An M-file can be created in any text editor, but it should be saved in a diskfile with the extension
.m. There are two types of M-files, scripts and functions. A script is nothing else but a file
containing series of statements.
Example 10.29. Suppose that we created the following script file called script1.m.
Q=[1 2; 3 4];
determinantQ = det(Q)
traceQ = trace(Q)
>> script1
(which is the file’s name without the extension .m) in the MATLAB command window, the
script is automatically loaded and its statements and commands are executed:
>> script1
determinantQ =
-2
traceQ =
5
10.7. M-FILES 155
The following file, script2.m, works interactively, i.e. it requires a user’s input to continue
computations.
Here the functions input, mat2str and num2str are used to read user’s input, and to
convert the matrix and a number to a string, respectively. Function disp is used to display
a vector of elements, each of which is a string in this case. When executed, the script asks
the user to input a square matrix:
>> script2
input a square matrix:
and when a square matrix is entered, it outputs the determinant and the trace of this matrix
in the following way:
A function file is created in a similar way as scripts, the only difference is that a function also
has input arguments. The first line of a function file is usually in the form
It declares the function name, input and output arguments. A function with the first line as
above should be saved in a file with the name functionname.m (corresponding to the function
name in the starting line). To execute a function, we type the function name followed by input
arguments in the parenthesis, in exactly the same way as we did it for built-in functions.
Example 10.30. Suppose we want to write a function, which takes two vectors and
multiplies them together. We create the following M-file:
function H = mul(v,x)
% v, x : vectors of the same dimension
% the function mul(v,x) multiplies them together
H = v’*x ;
Then we save this file as mul.m. To run it, in the MATLAB command window we first
define two vectors v and x of the same dimension, and then enter w = mul(v,x). Then the
variable w will be assigned the result of the multiplication of vectors v, x:
w =
1
156 CHAPTER 10. AN INTRODUCTION TO MATLAB
The % symbol is used for comments; the part of the line after the % sign is ignored by MATLAB.
The first few lines of comments in the M-file are used in the on-line help facility. For example, if
we enter help mul in the command widnow, MATLAB will reply with
Example 10.31. The following function is saved in the disk file called mulf.m.
if nargin ~= 3 | size(x)~=size(y)
error(’Please check your input’)
end
prodf = feval(func,x’)*feval(func,y);
fprod = feval(func,x’*y);
Now, suppose that we want to apply this function for f (x) = x2 , x = (1, 2, 3)0 , and y =
(3, 2, 1)0 . First, we need to create the following user-defined function for f (x) and save it
as f.m.
function f=f(x)
% Given x, f(x) returns the square of x.
f=x.^2;
pf =
34
fp =
100
10.8 Graphics
MATLAB has excellent visualization capabilities: it is able to produce planar plots and curves,
three-dimensional plots, curves, and mesh surfaces, etc. In this section we will introduce some of
the basic MATLAB graphics features.
Example 10.32. The following opens a graphics window and draws the graph of the
exponential function over the interval -2 to 2:
6
>> x=-2:0.01:2;
>> y=exp(x); 5
>> plot(x,y) 4
0
−2 −1.5 −1 −0.5 0 0.5 1 1.5 2
The vector x represents the interval over which the plot is built; in this example we use
a partition of [−2, 2] with meshsize 0.01. The vector y contains the values of the function
exp(x) in the points given by x.
3-D line plots are built using the command plot3, which operates similarly to plot in two dimen-
sions. Namely, given three vectors x, y and z of the same length, plot3(x,y,z) builds a plot of
the piecewise linear curve connecting the points with coordinates defined by the corresponding
components of x, y and z. In the example below we define x, y and z parametrically, using
vector t.
Example 10.33.
158 CHAPTER 10. AN INTRODUCTION TO MATLAB
>> t=0:0.01:10*pi; 5
>> x=cos(t); 4
>> y=sin(t); 3
2
>> z=sqrt(t);
1
>> plot3(x,y,z) 0
1
0.5 1
0.5
0
0
−0.5
−0.5
−1 −1
3-D mesh plots are created using the command mesh. When an m × n matrix Z is used as a single
argument (mesh(Z)), then the mesh surface uses the values of Z as z-coordinates of points defined
over a geometrically rectangular grid {1, 2, . . . , m} × {1, 2, . . . , n} in the x − y plane. Similarly,
3-D colored surfaces are created using the command surf.
To draw a 3-D graph of a function of two variables f (x, y) over a rectangle, we first use the
function [X,Y] = meshgrid(x,y) to transforms the domain specified by vectors x and y into
matrices X and Y which are used for the evaluation of f (x, y). In these matrices, the rows of X
are copies of the vector x and the columns of Y are copies of the vector y. The function f (x, y)
is then evaluated entrywise over the matrices X and Y, producing the matrix Z of the function
values, to which mesh(Z) or surf(Z) can be applied.
Example 10.34. Below we draw the mesh surfaces of a random matrix and the matrix
consisting of all ones, both of dimension 50 × 50 :
1 2
0.8
1.5
0.6
1
0.4
0.5
0.2
0 0
50 50
40 50 40 50
30 40 30 40
20 30 20 30
20 20
10 10
10 10
0 0 0 0
−x2 −y 2
A graph of f (x, y) = cos(2x) sin(y)e 5 over the rectangle [−π, π]×[−π, π] can be drawn
as follows.
10.8. GRAPHICS 159
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
−0.2 −0.2
−0.4 −0.4
−0.6 −0.6
−0.8 −0.8
80 80
60 70 60 70
60 60
40 50 40 50
40 40
30 30
20 20 20 20
10 10
0 0 0 0
160 CHAPTER 10. AN INTRODUCTION TO MATLAB
For more help on a topic, you can type “help topic” in the Matlab command window. This
will give a list of commands and functions for the given topic. Then again, you can enter “help
function name” to get a detailed description of how to use the function of interest.