Introduction to MATLAB
Kathmandu University
Mathematics Group
1 Introduction
MATLAB is an interactive matrix based system for scientific and en-
gineering numerical computation and visualization.
It is a powerful tool that might solve complex numerical problems in
a fraction of time required by other programming language such as
FORTRAN or C.
It has a very extensive library of predefined programs or functions de-
signed to help engineers and scientists to solve their problems in a
faster and less painful way, having over 40 different toolboxes for dif-
ferent subject of study. Different toolboxes contain different functions.
Every toolbox is area specific and may not be useful to all researchers.
For example:
Bioinformatics Toolbox
Curve fitting Toolbox
Communication Toolbox
Optimization Toolbox
Partial Differential Equation Toolbox and so on.
The name MATLAB stands for MATrix LABoratory, because every in-
put in MATLAB has to write in Matrix. Column or row matrix, which
consists of a collection of data values organized into column or row,
known as an array is the fundamental unit of data in MATLAB pro-
gram. So, an array is the column vector or row vector in any MATLAB
program.
1
2
Column Vector A = .. ; Row Vector B = 1 2 . . . n 1n ;
.
n n1
1 2 3 4
3 4 Order Matrix C = 5 6 7 8
9 10 11 12 34
1
and
1 1 Order Matrix = 12
The 1 1 order matrix is termed as scalar.
Arrays are classified as vector and matrix. A vector is an array with
only one dimension, and a matrix is an array with two or more dimen-
sions.
The size of an array is specified as the number of rows and the number
of columns in the array with the number of rows mentioned first. In-
dividual elements in an array are addressed by particular element. For
example, in the above arrays C(2,3) is 7 but C(4) is 2, because in this
notation, by default, MATLAB addresses column-wise.
A MATLAB variable is a region of memory containing an array that
is known by a user-specified name. In the above example, A, B and C
are MATLAB variables.
MATLAB variable name must begin with a letter followed by any com-
bination of letters, numbers and the underscore character. Only the
first 63 characters are significant.
2 Accessing MATLAB
Start:
Access MATLAB from the menu or click the MATLAB icon on the
desktop.
MATLAB command prompt > > pops up (in command window).
Quit:
Type quit or exit after the command prompt > >.
Click on respective close () button.
3 MATLAB Windows
The Command Window
The Command History Window
The Current Directory Window
The Editor/Debug Window
The Workspace
The Figure Window
2
4 Data Type in MATLAB
Every programming language has its specific way of recognizing different
data types. MATLAB as a computing language is no different from them.
MATLAB also has its own way of recognizing different data types. However,
in MATLAB, data handling is much easier than other languages like C, JAVA,
FORTARN etc.
4.1 Common Data Type in MATLAB
Scalar: Number to represent a quantity or measure. e.g integers,
complex numbers, floating point such as 4, 3+5i, -23.75
Characters: Single alphanumeric symbol enclosed in a single quote
is a character constant. e.g. A, 5, + etc. Note that 5 and 5 are
different data types.
Arrays: Array is the list of similar data in a single row or column
form. Elements of an array can be all numeric or characters or strings.
But should not be mixed up. Elements of an array can be another
array of similar type. The array of array is known as multidimensional
array. An array of two dimension is known as matrix.
Strings: Two or more alphanumeric symbols in a single quote is a
string data. A string is an array of characters.
Cell-array: Special type of array where elements can be of different
data types. They are kept in a braces separated by commas.
Structures: A structures is also a different data type to store vari-
ables related data type using meaningful field names. They are written
in the form of Name-vaule combination using the word struct. Ex-
ample: struct(City, Dhulikhel, Distance from Kathmandu, 30km,
District, Kavre).
Variables: Handling data directly in computing is inconvenient for
various reasons. The main inconvenience is that we have to retype
the same data every time we work on the data. If the data is very
long, it would really be a tiring job. To avoid such inconvenience while
handling data, we use a name to represent the data. In computer
programming, a variable denotes the address of location of a value or
a set of values. MATLAB has certain rules to call a combination of
characters or letters:
[i] A variable name should begin with letter followed by other
letters, digits and underscores.
[ii] The length of the variable should be between 1 to 32.
[iii] The name of the variable are case sensitive.
[iv] Keywords and program name should be avoided as variable
3
names.
[v] The variable name should not clash with the name of an already
existing function.
Keywords are the reserved words used in MATLAB for writing a pro-
gram. Avoid using a keyword for a variable or function name. MAT-
LAB keywords are: break case catch continue else elseif end
for function global if otherwise persistent return switch try
while
5 Entering Scalars, Vectors and Matrices
Scalar:
>> 5
ans =
5
Vectors:
(a) Row Vector
>> A = [1 2 3 4]
A =
1 2 3 4
OR
>> A = [1,2,3,4]
A =
1 2 3 4
(b) Column Vector
>> B = [1 2 3 4]
B =
1
2
3
4
>> B = [1;2;3;4]
B =
1
2
3
4
4
Matrix
>> C = [1,2,3;4,5,6;7,8,9]
C =
1 2 3
4 5 6
7 8 9
OR
>> C = [1 2 3;4 5 6;7 8 9]
C =
1 2 3
4 5 6
7 8 9
OR
>> C = [1,2,3
4,5,6 7,8,9] C =
1 2 3
4 5 6
7 8 9
OR
>> C = [1 2 3
4 5 6 7 8 9] C =
1 2 3
4 5 6
7 8 9
The following input creates a matrix, in particular, a row vector with incre-
ment of 1.
>> A = [1:8]
A =
1 2 3 4 5 6 7 8
Increment according to our desire: The following example makes an
increment of 2. The syntax reads as [start value:increment:end value]. If the
increment is missing, it is 1 by default.
>> A = [-5:2:5]
A =
-5 -3 -1 1 3 5
Others which generates linearly spaced vectors are linspace( ) and
logspace( ):
linspace(a, b, n) generates a linearly spaced vector of length n from a
to b.
Example 1 u = linspace(0,20,5) generates a row vector u = [0 5 10
15 20]. Thus u = linspace(a,b,n) is the same as u = a:(b-a)/(n-1):b.
5
logspace(a, b, n) generates a logarithmically spaced vector of length n
from 10a to 10b .
Example 2 v = logspace(0,3,4) generates a row vector v = [1 10 100
1000]. Thus logspace(a,b,n) is the same as 10.linspace(a,b,n).
Ellipses
If a statement is too long to type on a single line, it may be continued on
successive lines by typing an ellipsis (. . .) at the end of the first line, and
then continuing on the next line. For example, the following two statements
are identical.
>> X = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9;
>> X = 1 + 1/2 + 1/3 + 1/4 + 1/5 + ...
1/6 + 1/7 + 1/8 + 1/9;
6
Meanings of Comma(,), Colon(:) and Semicolon(;):
Comman (,) or space bar is used to write the elements of a row.
Colon (:) is used for increment in a row vector.
Semicolon (;) is used for new row in a matrix. The other important
significant of semicolon(;) is not to display the answer in command
window but retains the input in computer memory. This we can do as
>> A = [1 2 3;4 5 6;7 8 9];
>> 4 + 5 + 6 + 7 + 8;
6 Arithmetic Operations and Built-in-functions
MATLAB knows real and complex numbers i.e., 2, 3.2, 4 + 2i, 4 + 2j(i,
j both will accept as imaginary unit), and number in exponential form e.g
2.35 106 = 2.35e 6, blank space must avoided.
Arithmetic Operations:
Operations Meaning
+ addition
subtraction
multiplication
\ left division
/ right division
power
Note the distinction between left division (\) and right division (/). This you
can distinct with 6\2 = 0.3333 and 6/2 = 3. These operations for addition,
subtraction and multiplication are explicitly used in compatiable matrices for
matrix addition, subtraction and multiplication respectively. Note that if A
is a non singular square matrix, then A2 is same as AA. If b is compatiable
column and respectively row vector, then
X = A \ b gives the solution of the linear system of equations AX =
b, i.e., X = A1 b.
X = b / A gives the solution of the linear system of equations XA =
b, i.e., X = bA1 .
Built-in-functions:
If arbitrary built in functions for scalars, e.g. exp( ), sqrt( ), sin( ) are
applied on matrix, they are evaluated componentwise.
A few built in functions in MATLAB deal with the whole matrix and
not only with its components, e.g. expm( ), sqrtm( ), logm( ).
7
The name of all built-in MATLAB function starts with a small letter,
and the arguments of the functions are stated in round bracket (.). For
example,
>> real(-3+2*i)
ans =
7
>> imag(-3+2*j)
ans =
2
Built-in-functions for Scalar:
Commands Functions Commands Functions
abs( ) absolute value sqrt( ) square root
real( ) real part imag( ) imaginary part
angle( ) phase angle conj( ) complex conjugate
round( ) round to integer sign( ) signum function
floor( ) floor function ceil( ) ceiling function
exp( ) exponential function log( ) logrithmic function
>> sqrt(3)
ans =
1.7321
By default, MATLAB produces 4 digits after decimal places. If we
want the more digits after the decimal places, then do as
>> format long
>> sqrt(3)
ans =
1.73205080756888
There are other format commands too.
Trigonometric functions:
Commands Functions Commands Functions
sin( ) sine cos( ) cosine
tan( ) tangent cot( ) co-tangent
sec( ) secant csc( ) cosecant
asin( ) inverse sine acos( ) inverse consine
sinh( ) hyperbolic sine asinh( ) inverse hyperbolic sine
The angles given to these functions as arguments must be in radians.
8
Vector functions:
Commands Functions Commands Functions
length( ) length of a vector norm( ) norm of a vector
max( ) maximum min( ) minimum
sum( ) sum of components prod( ) product of components
sort( ) sorting mean( ) mean
median( ) median std( ) standard deviation
any( ) any non-zero value! all( ) all non-zero value!
Matrix functions:
Commands Functions Commands Functions
size( ) size rank( ) rank
inv( ) inverse det( ) determinant
norm( ) norm cond( ) condition
eig( ) eigenvalues chol( ) cholosky decomposition
lu( ) LU decomposition qr( ) QR decomposition
schur( ) schur complement hess( ) hessenberg form
Matrix built-in functions:
Commands Functions Commands Functions
zeros( ) matrix of zeros ones( ) matrix of ones
eye( ) identity matrix diag( ) create or extract diagonals
rand( ) uniform random value randn( ) normal random value
zeros(m,n) produces m n matrix of zeros and zeros(n) one of size
n n.
Take the online-help: > > help diag
Example 3 See the following effects of diag command.
>> B = [ones(3) zeros(3,2);zeros(2,3) 4*eye(2)]
B =
1 1 1 0 0
1 1 1 0 0
1 1 1 0 0
0 0 0 4 0
0 0 0 0 4
>> diag(B)
ans =
1 1 1 4 4
9
>> diag(B,1)
ans =
1
1
0
0
>> diag(B,-2)
ans =
1 0 0
>> d = [2 4 6 8];
>> d1 = [-3 -3 -3];
>> d2 = [-1 -1];
>> D = diag(d) + diag(d1,1) + diag(d2,-2)
D =
2 -3 0 0
0 4 -3 0
-1 0 6 -3
0 -1 0 8
Addressing Matrix Components:
A(m,n): the component amn of the matrix A = (aij )ij . Note that the
numbering of the components starts from 1.
A(m:n,p): the m until the nth row of the pth column of the matrix
A.
A(:,n): the complete nth column of the matrix A.
A([m,n],:): the m and the nth row of the matrix A.
X(m): the mth component of the vector X.
X = X(n:-1:1): changes the order of the elements of the vector X of
length n.
Some more built-in-functions:
rot90() rotates a matrix by 90 degree.
fliplr(): flips a matrix from left to right.
flipud(): flips a matrix from up to down.
tril(): extracts the lower triangular part of a matrix.
triu(): extracts the upper triangular part of a matrix.
reshape(): changes the shape of a matrix. reshape(A,p,q) occurs as
long as m n = p q where Amn . See the online help: > > help
reshape
10
7 Array, Relational and Logical Operations
Array Operations: Element-by-element multiplication, division and ex-
ponentiation between two matrices or vectors of the same size are done by
preceeding the corresponding arithmetic operations by a period (.).
Operations Meaning
. element-by-element multiplication
.\ element-by-element left division
./ element-by-element right division
. element-by-element exponentiation
Relational Operations: There are six relational operators in MATLAB.
Operations Meaning
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal
= not equal
These relational operations result in a vector or matrix of the same size as
the operands, with 1 where the relation is true and 0 where it is false. For
example,
>> [4 3 2]>[1 5 0]
ans =
1 0 1
>> 5==3
ans =
0
Note that the equality sign = is used in an assignment statement, whereas
== is used in a relation. Relations may be connected or quantified by logical
operators.
11
Logical Operations: These are the following logical operators in MATLAB.
Operations Meaning
& logical AND
&& logical AND with shorcut evaluation
| logical OR
|| logical OR with shortcut evaluation
Xor exclusive OR
logical complement(not)
These operators work in a similar way as the relational operators and
produces vectors or matrices of the same size as the operands, with 1 where
condition is true and 0 where false. For example:
>> (2==2)&(2>1)
ans =
1
>> (2==3)&(2>1)
ans =
0
>> (2==3)|(2>1)
ans =
1
12