MATLABBasics
MATLABBasics
1. INTRODUCTION
( a )What is MATLAB?
In languages like FORTRAN & C we have to declare dimensions of matrices used. But, here,
by default each entry is a matrix, therefore dimensioning of a variable is not required. We can
solve complex numerical problems in a fraction of the time required with a programming
language such as FORTRAN or C. MATLAB is also a programmable system. It contains so
many useful algorithms as built-in functions and hence programming itself is easier. The
graphic and multimedia capabilities are also commendable.
MATLAB is recognized as the interactive program for numerical linear algebra and matrix
computation. In industries, MATLAB is used for research and to solve practical engineering
and mathematical problems. Also, in automatic control theory, statistics and digital signal
processing (Time-Series Analysis) one can use MATLAB. The following tool boxes make it
useful in soft computing at various industrial and scientific areas:
(i) Neural Networks (ii) Optimization
(iii) Genetic Algorithms (iv) Wavelets
(v) Fuzzy Logic (vi) Control systems
(vi) Signal Processing
By clicking the MATLAB shortcut icon on the desktop of your computer (or selecting from
the program menu) you can access MATLAB. This results in getting MATLAB command
window with its prompt:
R. K. George, B. S. Ratanpal 1
>>
with a blinking cursor appearing right of the prompt, telling you that MATLAB is waiting to
perform a mathematical operation you would like to give.
R. K. George, B. S. Ratanpal 2
Simple Math Calculations
( i ) If you want to add two numbers say 7 & 12, type as follows
>> 7+12
and press the ENTER or return key, you see the following output:
ans =
19
Here, ans stands for the answer of computation. Similarly, the following gives product and
difference of these numbers,
( ii ) If you want to store the values 7 and 12 in MATLAB variables a & b and store the
values of their product and division in c and d, do as follows:
>> a =7 <ENTER>
a=
7
You can exit MATLAB with the command exit or quit. A computation can be stopped with
[ctrl-c]
R. K. George, B. S. Ratanpal 3
The basic arithmetic operation are given by:
Expressions are composed of operators, function and variable names. After evaluation the
value is assigned to the variable and displayed. If the variable name and = sign are omitted, a
variable ans (for answer) is automatically created and the result is assigned to it.
A statement is normally terminated with the carriage returns. However, a statement can be
continued on the next line with three or more periods followed by a carriage return.
Several statements can be placed on a single line if separated by commas or semicolons. If
the last character of a statement is a semicolon, then values of the variable printing to the
screen will be suppressed, but the assignment is still carried out.
Rules of Precedence:
Expressions are evaluated from left to right with exponential operation having the highest
precedence, followed by multiplication and division having equal precedence, followed
by addition and subtracting having equal precedence. Parentheses can be used to alter this
ordering in which case these rules of precedence are applied within each set of parentheses
starting with the innermost set and proceeding outward.
( iii ) The most recent values assigned to the variables you used in the current session are
available. For example, if you type a at the prompt you get the output as :
>> a
a=
7
R. K. George, B. S. Ratanpal 4
If you cannot remember the names of the variables, you have used in the current session, you
can use the who command for a list of variables it has in the current session.
>> who
Your variables are
ans a b c
d
The command whos will list the variables in the workspace and their size.
The command
>> clear
will remove all current variables from the memory of the system.
>> clear a
( iv) To recall previous commands, MATLAB uses the cursor keys ←, ↑, →, ↓ on your
keyboard.
( v ) The display of numerical values can have different format as we see below:
>> e= 1/3
e=
0.3333
>> e
e=
0.33333333333333
R. K. George, B. S. Ratanpal 5
>>format ( default format)
>>e
e=
0.3333
( vi ) To suppress the display of output of a command on screen put semicolon ‘;’ after
the command.
>> a=3;
>>
>> exit
When we log out or exit, MATLAB will lose all the current variables from the memory. To
save the current session, type
>> save
This saves the all current variables to a binary diskfile matlab.mat. When you later re-enter
MATLAB, the command
>> load
>> c = 1-2i
c=
1.000–2.0000 i
>> abs ( c )
ans =
2.2361
>> real ( c )
ans =
1
R. K. George, B. S. Ratanpal 6
>> imag ( c )
ans =
-2
>> angle ( c )
ans =
-1.1071
>> help
R. K. George, B. S. Ratanpal 7
The following are some of the most commonly used functions:
trigonometric. exponential.
sin - sine. exp - exponential.
sinh - hyperbolic sine. log - natural logarithm.
asin - inverse sine. log10 - common (base 10) logarithm.
asinh - inverse hyperbolic sine. log2 - base 2 logarithm and dissect
cos - cosine. floating point number.
cosh - hyperbolic cosine. pow2 - base 2 power and scale
acos - inverse cosine. floating point number.
acosh - inverse hyperbolic cosine. sqrt - square root.
tan - tangent. nextpow2 - next higher power of 2
tanh - hyperbolic tangent. complex.
atan - inverse tangent. abs - absolute value.
atan2 - four quadrant inverse tangent. angle - phase angle.
atanh - inverse hyperbolic tangent. conj - complex conjugate.
sec - secant. imag - complex imaginary part.
sech - hyperbolic secant. real - complex real part.
asec - inverse secant. unwrap - unwrap phase angle.
asech - inverse hyperbolic secant. isreal - true for real array.
csc - cosecant. cplxpair - sort numbers into complex
csch - hyperbolic cosecant. conjugate pairs.
acsc - inverse cosecant. rounding and remainder.
acsch - inverse hyperbolic cosecant. fix - round towards zero.
cot - cotangent. floor - round towards minus infinity.
coth - hyperbolic cotangent. ceil - round towards plus infinity.
acot - inverse cotangent. round - round towards nearest integer.
acoth - inverse hyperbolic cotangent. mod - modulus (signed remainder
after division).
rem - remainder after division.
sign - signum.
Scalers - 1 by 1 matrix
Row vector - matrix with one row
Column vector - matrix with one column.
>> a = [1 2 3; 4 5 6; 7 8 9]
R. K. George, B. S. Ratanpal 8
a=
1 2 3
4 5 6
7 8 9
The rows are separated by semicolons and elements are separated by space or by comma.
That is, the above matrix can also be stored by the following command.
>> a = [1,2,3;4,5,6;7,8,9];
or by the statement
>> a = [
1 2 3
4 5 6
7 8 9 ];
>> b = a’
b=
1 4 7
2 5 8
3 6 9
Function Task
+ Addition
- Subtraction
* Multiplication
^ Power
‘ Transpose
\ Left Division
/ Right Division
Examples:
2 6 10
6 10 14
10 14 18
R. K. George, B. S. Ratanpal 9
>> b1 = a-b (b is subtracted from a and stores in b1)
b1 =
0 -2 -4
2 0 -2
4 2 0
c=
14 32 50
32 77 122
50 122 194
16.1168
-1.1168
0.0000
R. K. George, B. S. Ratanpal 10
d=
16.1168 0 0
0 -1.1168 0
0 0 0.0000
3 3
The following are some special matrices generated by built-in statements and functions
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
>> a = hilb(5)
a=
R. K. George, B. S. Ratanpal 11
Table of functions dealing with matrices
ans =
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
ans =
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We can also load a matrix from an external ASCII file, say data.ext (where .ext is any
extension). If this ascii file contain a rectangular array of just the numeric matrix entries, then
to load the matrix type the command
R. K. George, B. S. Ratanpal 12
>> a = [1 2 3 4;5 6 7 1;2 3 4 5]
a=
1 2 3 4
5 6 7 1
2 3 4 5
>> b= a(1:2,3) (Vector consisting of the first 2 entries of the 3rd column of a)
b=
3
7
c=
3
7
4
1 2 3 4
5 6 7 1
e=
2 3 4 5
f=
2 4
6 1
3 5
aa =
3 4
7 1
R. K. George, B. S. Ratanpal 13
Matrices can be built from blocks of matrices
b=
1 2 3 0 0
4 5 6 0 0
7 8 9 0 0
1 1 1 1 0
1 1 1 0 1
Functions of vectors
>> t = [1:2:10] (Makes a row vector t having element starting from 1 up to 10 with step size
2)
t=
1 3 5 7 9
5 4 3 2 1 0
25
R. K. George, B. S. Ratanpal 14
>> mean(t) (mean of elements of t)
ans =
1 3 5 7 9
ans =
945
ans =
>> any(t)
ans =
>> all(t)
ans =
ans =
3.1623
R. K. George, B. S. Ratanpal 15
Function Task Function Task
chol Cholesky condeig Condition number
factorization with respect to
eigenvalues
cholinc Incomplete Cholesky hess Hessenberg form
factorization
lu LU factorization qz QZ factorization for
generalized
eigenvalues
luinc Incomplete LU schur Schur decomposition
factorization
qr Orthogonal-triangular expm Matrix exponential
decomposition
nnls Non-negative least- logm Matrix logarithm
squares
pinv Pseudoinverse sqrtm Matrix square root
lscov Least squares with funm Evaluate general
known covariance matrix function
eig Eigenvalues and qrdelete Delete column from
eigenvectors QR factorization
svd Singular value qrinsert Insert column in QR
decomposition factorization
eigs A few eigenvalues rsf2csf Real block diagonal
form to complex
diagonal form
cdf2rdf Complex diagonal balance Diagonal scaling to
form to real block improve eigenvalue
diagonal form accuracy
planerot Given's plane
rotation
4.Plotting Graphs
2-D plots :
Suppose we want to plot the graph of y = sin(x), in a interval [0,10]. Type as follows
>> x = 0:0.5:10; (generates points in the given interval)
>> y = sin(x); (calculate function values at the x points)
>> plot(x,y) (Plots x verses y)
This will display the following graph:
R. K. George, B. S. Ratanpal 16
1
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7 8 9 10
We can also give the title, x-label, y-label to the graph, to do this you type as follows on
MATLAB command prompt:
R. K. George, B. S. Ratanpal 17
Graph Of S ine Function
1
0.8
0.6
0.4
0.2
Y = S in(x )
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7 8 9 10
X V alues
More on plots
Example:
plot(x,y,'c+:') plots a cyan dotted line with a plus at each data point.
plot(x,y,'bd') plots blue diamond at each data point but does not draw any line.
R. K. George, B. S. Ratanpal 18
More than one plot in the same graph
puts two plots, plot(x, y, ‘b’) and plot(x, z, ‘g’) in one graph. The first one with blue color
and the second with green color.
Example:
>> t = linspace(0,2*pi); (line space generates 100 t points between 0 and 2Π)
>> x = sin(t);
>> y = cos(t);
>> plot(t, x,’*’, t, y,’-’) (plots sine and cos graphs in the same plot)
>> legend(‘x = sin(t)’, ’y = cos(t)’) (provides legends for graphs)
>> grid (provides grid lines)
x=sin(t)
0.8 y=cos(t)
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
-1
0 1 2 3 4 5 6 7
Subplots
You can hold more than one set of axes on one figure window. The command
subplot(m,n,p) subdivides the current figure window into an m-by-n matrix of plotting areas
and chooses the pth area to be active.
R. K. George, B. S. Ratanpal 19
Example:
>> x = -2*pi:pi/10:2*pi;
>> y = x.^2;
>> z = sin(x);
>> y1 = cos(x);
>> z1 = exp(x);
>> subplot(2,2,1),plot(x,y)
>> grid
>> subplot(2,2,2),plot(x,z)
>> grid
>> subplot(2,2,3),plot(x,y1)
>> grid
>> subplot(2,2,4),plot(x,z1)
>>grid
40 1
35
30 0.5
25
20 0
15
10 -0.5
0 -1
-10 -5 0 5 10 -10 -5 0 5 10
1 600
500
0.5
400
0 300
200
-0.5
100
-1 0
-10 -5 0 5 10 -10 -5 0 5 10
R. K. George, B. S. Ratanpal 20
Function Task Function Task
plotyy Graphs with y tick xlabel X-axis label
labels on the left and
right
axis Control axis scaling ylabel Y-axis label
and appearance
zoom Zoom in and out on a text Text annotation
2-D plot
grid Grid lines gtext Place text with
mouse
box Axis box
3-D plots
Similar to 2-D plots, plot3 produces curves in 3-dimentional space
>> plot3(x,y,z)
produces the plot of the piecewise linear curves in 3-D space passing through the coordinates
of the respective elements of x, y and z.
Example
>> t :-20*pi:0.01:20*pi;
>> x = cos(t);
>> y = sin(t);
>> z = t.^3;
>> plot3(x, y, z)
5
x 10
2.5
1.5
0.5
-0.5
-1
-1.5
-2
-2.5
1
0.5 1
0.8
0.6
0 0.4
0.2
0
-0.2
-0.5 -0.4
-0.6
-0.8
-1 -1
We can also give the title, x-label, y-label, z-label, grid to the 3-D graphs as we are
doing in 2-D graphs.
R. K. George, B. S. Ratanpal 21
3D Mesh Plots
>> mesh(z)
creates a 3-dimentional plot of the elements of the matrix z. The mesh surface is defined by
the z-co-ordingates. You can plot mesh surface by the z-co-ordinates of points above a
rectangular grid in the x-y plane. It forms the mesh plot by joining adjacent points with
straight lines.
Example 1:
>> xx = -2:0.2:2;
>> yy = xx;
>> [x, y] = meshgrid(xx,yy);
>> z = x.^2+y.^2;
>> mesh (z)
>> [x,y] = meshgrid(-2:.2:2,-2:.2:2); can be used to replace the first 3 lines given in the
above example.
R. K. George, B. S. Ratanpal 22
Example 2:
Surface plots
Surface plots look like a mesh plot, the only difference is that the spaces between the lines
are filled in. Surface plots are generated by using surf function. We plot the above graph
using surf
R. K. George, B. S. Ratanpal 23
Functions for 3-D plots
R. K. George, B. S. Ratanpal 24
Function Task Function Task
flag Alternating red, lines Color map with the
white, blue, and line colors
black color map
colorcube Enhanced color-cube jet Variant of HSV
color map
prism Prism color map cool Shades of cyan and
magenta color map
autumn Shades of red and spring Shades of magenta
yellow color map and yellow color map
winter Shades of blue and summer Shades of green and
green color map yellow color map
axis Control axis scaling zoom Zoom in and out on a
and appearance 2-D plot
grid Grid lines box Axis box
hold Hold current graph axes Create axes in
arbitrary positions
subplot Create axes in tiled view 3-D graph viewpoint
positions specification
viewmtx View transformation rotate3d Interactively rotate
matrix view of 3-D plot
title Graph title xlabel X-axis label
ylabel Y-axis label zlabel Z-axis label
colorbar Display color bar text Text annotation
(color scale)
gtext Mouse placement of
text
MATLAB Programming
We can also do programming in MATLAB as we are doing in FORTRAN, C & C++. To
make a file in MATLAB we have to click on “New” in the file menu in menubar. It will open
a new file as we are doing in “word”; and if we save this file (called m-file), will be saved in
“bin” folder of MATLAB.
Such files are called “M-files” because they have an extension of “.m” in its filename. Much
of your work with MATLAB will be creating and refining M-files.
There are two types of M-files: Script Files and Function Files
Script Files
A script file consists of a sequence of normal MATLAB statements. If the file has the
filename, say, rkg.m, then the MATLAB command >> rkg will cause the statements in the
file to be executed. Variables in a script file are global and will change the value of variables
of the same name in the environment of the current MATLAB session.
Script files are often used to enter data into a large matrix; in such a file, entry errors
can be easily edited out.
R. K. George, B. S. Ratanpal 25
Example: In a file rkg.m enter the following:
% This is a sample m-file
a = [1,2,3;0,1,1;1,2,3]
b =a’;
c = a+b
d = inv(c)
save this file. Then to execute this file, type
a=
1 2 3
0 1 1
1 2 3
b=
1 0 1
2 1 2
3 1 3
c=
2 2 4
2 2 3
4 3 6
d=
-1.5000 0 1.0000
0 2.0000 -1.0000
1.0000 -1.0000 0
The % symbol indicates that the rest of the line is a comments. MATLAB will ignore the rest
of the line. However, the first comment lines which document the m-file are available to the
on-line help facility and will be displayed
A M-file can also reference other M-files, including referencing itself recursively.
Function Files
Function files provide extensibility to MATLAB. You can create new functions
specific to your problem which will then have the same status as other MATLAB functions.
Variables in a function file are by default local. However, you can declare a variable to be
global if you wish.
R. K. George, B. S. Ratanpal 26
Example
Save this file with filename prod.m then type on the MATLAB prompt
>> prod (3,4)
ans =
12
As we know that if we don’t write “;” after a statement in MATLAB, it will print the
output also. That means if in a programme we write:
a=input (‘ Enter a number ‘);
And on command prompt if we run this program it will be displayed like:
Control Flow
1) if statement condition:
if expression
statements
elseif expression
statements
else
statements
end
The statements are executed if the real part of the expression has all non-zero elements.
The else and elseif parts are optional. zero or more elseif parts can be used as well as nested
if's. The expression is usually of the form
expr rop expr
where rop is ==, <, >, <=, >=, or ~=.
R. K. George, B. S. Ratanpal 27
Example:
if i == j
a(i,j) = 2;
elseif abs(i-j) == 1
a(i,j) = -1;
else
4) end terminate scope of for, while, switch, try, and if statements. Without end's, for, while,
switch, try, and if wait for further input. each end is paired with the closest previous unpaired
for, while, switch, try or if and serves to terminate its scope. end can also serve as the last
index in an indexing expression. in that context,
end = size(x,k) when used as part of the k-th index. examples of this use are, x(3:end) and
x(1,1:2:end-1). when using end to grow an array, as in x(end+1) = 5, make sure x exists first.
R. K. George, B. S. Ratanpal 28
Example: (assume n has already been assigned a value)
for i = 1:n,
for j = 1:n,
a(i,j) = 1/(i+j-1);
end
end
for s = 1.0: -0.1: 0.0, end steps s with increments of -0.1
for e = eye(n), ... end sets e to the unit n-vectors.
Long loops are more memory efficient when the colon expression appears in the for
statement since the index vector is never created.
6) The break statement can be used to terminate the loop prematurely. break terminate
execution of while or for loop. In nested loops, break exits from the innermost loop only.
while expression
statements
end
The statements are executed while the real part of the expression has all non-zero elements.
The expression is usually the result of expr rop expr where rop is ==, <, >, <=, >=, or ~=.
Example:
(assuming a already defined)
e = 0*a; f = e + eye(size(e)); n = 1;
while norm(e+f-e,1) > 0,
e = e + f;
f = a*f/n;
n = n + 1;
end
The first case where the switch_expr matches the case_expr is executed. when the case
expression is a cell array (as in the second case above), the case_expr matches if any of the
R. K. George, B. S. Ratanpal 29
elements of the cell array match the switch expression. If none of the case expressions match
the switch expression then the otherwise case is executed (if it exists). Only one case is
executed and execution resumes with the statement after the end. the switch_expr can be a
scalar or a string. A scalar switch_expr matches a case_expr if switch_expr==case_expr. A
string switch_expr matches a case_expr if strcmp(switch_expr,case_expr) returns 1 (true).
Example:
(assuming method exists as a string variable):
switch lower(method)
case {'linear','bilinear'}, disp('method is linear')
case 'cubic', disp('method is cubic')
case 'nearest', disp('method is nearest')
otherwise, disp('unknown method.')
end
case is part of the switch statement syntax, whose general form is:
switch switch_expr
case case_expr,
statement, ..., statement
case {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
otherwise,
statement, ..., statement
end
otherwise is part of the switch statement syntax, whose general form is:
switch switch_expr
case case_expr,
statement, ..., statement
case {case_expr1, case_expr2, case_expr3,...}
statement, ..., statement
...
otherwise,
statement, ..., statement
end
The otherwise part is executed only if none of the preceeding case expressions match the
switch expression.
R. K. George, B. S. Ratanpal 30
11) try begin try block:
Normally, only the statements between the try and catch are executed. however, if an error
occurs while executing any of the statements, the error is captured into lasterr and the
statements between the catch and end are executed. if an error occurs within the catch
statements, execution will stop unless caught by another try...catch block. The error string
produced by a failed try block can be obtained with lasterr.
Example:
function d = det(a)
if isempty(a)
d = 1;
return
else
...
end
Suppose we have created a m-file & saved. Now to run this program, on command prompt
type the file name and just press the ENTER KEY that will run the file.
Data File:
Now to make a data file in MATLAB, we just make a file in which all the data are stored.
Now we make another file in which the operation on that data is to be done. Then in this file,
where we have to call that data we have to just type the file name of the file in which data is
stored and write the rest of the programming statements. So when run this file the file in
which data is stored will be called and then rest of the programming statements are executed
& finally we get the output.
R. K. George, B. S. Ratanpal 31
MEX-Files:
We can call our C programs from MATLAB as if they were built in functions. Those
programs in C which are callable in MATLAB are referred as MEX-Files. MEX-files are
dynamically linked subroutines that the MATLAB interpreter can automatically load &
execute. For example the following program in C to add two integers having file name “add”.
#include<stdio.h>
main( )
{ int a=2,b=3;
d=a+b;
printf(‘sum is:’,d);
return 0;
}
To compile & link this example at the MATLAB prompt, type
>>mex add.c
and press the “ENTER”key, it will give the output.
Some useful commands for programming:
>> echo on --- Echoing of commands in all script files
>> echo off --- Turns off echo
>> echo on all --- turns on of command including function files
>> disp(‘Any string’) --- Displays the string
>> diary file --- Causes copy of all subsequent keyboard input and most
of the resulting output (but not graphs) to be written on
the named file.
>> pause --- causes to stop execution of until any key is pressed.
Some Examples:
1) Example for if, else
for i = 1:n
for j = 1:n
if i==j
a(i, j) = 2
elseif abs(i – j) ==1
a(i, j) = -1;
else
a(i, j) = 0;
end
end
end
eps = 1
while (1+eps)>1
eps = eps/2;
end
eps = eps*2
R. K. George, B. S. Ratanpal 32
3) Gauss Elimination Method
RELATIONAL OPERATORS
MATLAB relational operators can be used to compare two arrays of the same size, or
to compare an array to a scalar. When we compare an array to a scalar, scalar expansion is
used to compare the scalar to each array element and the result has the same size as the array.
Example:
>> a = 1:0.5:10;
>> b = 5:0.5:14;
>> c = a > 5
R. K. George, B. S. Ratanpal 33
c=
Columns 1 through 12
0 0 0 0 0 0 0 0 0 1 1 1
Columns 13 through 19
1 1 1 1 1 1 1
>> d = (a ==b)
d=
Columns 1 through 12
0 0 0 0 0 0 0 0 0 0 0 0
Columns 13 through 19
0 0 0 0 0 0 0
LOGICAL OPERATORS
Example:
>> a = 1:15;
>> b = ~ ( a < 5 )
b=
Columns 1 through 12
0 0 0 0 1 1 1 1 1 1 1 1
Columns 13 through 15
1 1 1
R. K. George, B. S. Ratanpal 34
c=
Columns 1 through 12
0 0 1 1 1 1 1 0 0 0 0 0
Columns 13 through 15
0 0 0
Columns 1 through 12
1 1 1 1 1 1 1 1 1 1 1 1
Columns 13 through 15
1 1 1
R. K. George, B. S. Ratanpal 35