Matlab Tutorial
Matlab Tutorial
D B Gurung
Introductory MATLAB
Kathmandu University
Lecture Note for M.Phil. in Mathematics, 2012
0.1
Introduction
MATLAB is an interactive matrix based system for scientific and engineering 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.
The name MATLAB stands for MATrix LABoratory, because every input 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 program. 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
and
1 1 Order Matrix =
12
0.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.
0.3
MATLAB Windows
0.4
Scalar:
>> 5
ans =
5
Vectors:
(a) Row Vector
>> A = [1 2 3 4]
A =
1
2
3
OR
>> A = [1,2,3,4]
A =
1
2
3
>> B = [1 2 3 4]
B =
1
2
3
4
>> B = [1;2;3;4]
B =
1
2
3
4
Matrix
>> C =
C =
1
4
7
OR
>> C =
C =
1
4
7
OR
>> C =
4,5,6
7,8,9]
C =
1
4
7
OR
>> C =
4 5 6
7 8 9]
C =
1
4
7
[1,2,3;4,5,6;7,8,9]
2
5
8
3
6
9
[1 2 3;4 5 6;7 8 9]
2
5
8
3
6
9
[1,2,3
2
5
8
3
6
9
[1 2 3
2
5
8
3
6
9
The following input creates a matrix, in particular, a row vector with increment of 1.
>> A = [1:8]
A =
1
2
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
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.
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;
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;
0.5
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 .
Commands
Functions
sqrt( )
square root
imag( )
imaginary part
conj( )
complex conjugate
sign( )
signum function
ceil( )
ceiling 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
sin( )
sine
tan( )
tangent
sec( )
secant
asin( )
inverse sine
sinh( )
hyperbolic sine
Commands
Functions
cos( )
cosine
cot( )
co-tangent
csc( )
cosecant
acos( )
inverse consine
asinh( )
inverse hyperbolic sine
Matrix functions:
Commands
Functions
size( )
size
inv( )
inverse
norm( )
norm
eig( )
eigenvalues
lu( )
LU decomposition
schur( )
schur complement
Commands
Functions
rank( )
rank
det( )
determinant
cond( )
condition
chol( )
cholosky decomposition
qr( )
QR decomposition
hess( )
hessenberg form
d = [2 4 6 8];
d1 = [-3 -3 -3];
d2 = [-1 -1];
D = diag(d) + diag(d1,1) + diag(d2,-2)
7
D =
2
0
-1
0
-3
4
0
-1
0
-3
6
0
0
0
-3
8
0.6
Operations
.
.\
./
.
Meaning
element-by-element multiplication
element-by-element left division
element-by-element right division
element-by-element exponentiation
Meaning
logical AND
logical AND with shorcut evaluation
logical OR
logical OR with shortcut evaluation
exclusive OR
logical 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
Differences between & and &&: The following are the two major differences between these
two operators.
&
1. Works between scalar and array values
2. Does not support partial evaluation
or short cut evaluation
&&
1. Works between scalar values only
2. Supports partial evaluation
or short cut evaluation
10
MATLAB (Exercise - 1)
MATLAB Interactive with Calculator
1. Try the calculation operations and built-in-functions:
3 + 4; 8/2; 8\2; 33; (2*2 + 2*i); (2*2 + 2*i)-(2 + i); 2*2e+2; 2*2e-2; (2e+14/15);
(2e+14)/15
Absolute value: abs(-0.5), abs(2+2*j) Floor value: floor(4.5);
Ceiling value: ceil(4.45); Square root: sqrt(2); sqrt(-2); Real part: real(2 + 7i);
Imaginary part: imag(2 - 3i); Signum function: sign(-3.2); sign(3.2); sign(0);
Use also: exp(); sin(); tan();
Try to understand the difference between:
2. Type in vectors:
Enter the Vectors: A = [5 2 1 4 0 3 10 9]. Also enter the elements of A in column
vector.
Find: length(A), max(A), min(A), norm(A), sort(A), mean(A), std(A), median(A),
sum(A), prod(A).
3. Type in matrices:
Enter the matrix: A = [2 sqrt(2) 4;0 1e-1 3;-2.1 1.732 2]
Find: size(A), rand(size(A)), inv(A), det(A), norm(A).
4. Assume that array C is defined as shown, and determine the contents of the following
sub-arrays:
1 2 3 4
5 6 7 8
A=
9 10 11 12
13 14 15 16
MATLAB (Exercise - 2)
MATLAB Interactive Computation
1. Run time error: Errors due to indeterminate forms. The MATLAB output is NaN,
that is not a number.
(a) Evaluate the values of
1)/3.
sin x
x
(b) Evaluate the values of sinx x in the interval [-1, 1] considering the vectors x = x+(x ==
0) eps where initially x = (1 : 1)/3. Try to understand the outputs in (a) and
(b).
2. Equation of a straight line: The equation of a straight line is y = mx + c where m
and c are constants. Compute the y-coordinates of a line with slope m = 0.5 and the
intercept c = 2 at the following x-coordinates.
x = 0, 1.5, 3, 4, 5, 7, 9, and 10
3. Application: Write the following system of linear equation 3x + y + z = 3; 2x - 3y
- z = -3; x + 2y + z = 4 in matrix form. Check whether the system is consistent or
not. If consistent then use MATLAB to find the solution of this system. [Helpful builtin-functions: rank(A), and rank([A,b]) where A is the coefficient matrix and [A,b] is the
augmented matrix.]
4. Exponential and Logarithms: The mathematical quantities ex , lnx and logx are calculated with exp(x), log(x) and log10(x) respectively. Calculate the following quantities.
e2 , ln(e2 ), log10(e2 ) and log10(105 ).
e
163
ln17
.)
ln3
5. Trigonometry: The basic MATLAB trigonometric functions are sin, cos, tan, cot, sec
and csc. The inverses e.g. arcsin, arctan etc are calculated with asin, atan etc. The
same is true for hyperbolic functions. The argument of these functions must be in radian.
Calculate the following quantities:
sin 6 , cos 4 and tan 2 .
sin2 6 + cos2 6 . (Typing sin2 (x) for sin2 x will produce an error. Correct form is
(sin(x))2).
y = cos h2 x sin h2 x with x = 32.
6. Complex Number: MATLAB recognizes the letter i and j as the imaginary unit 1.
A complex number 2 + 5i may be input as 2 + 5i or 2 + 5*i in MATLAB. Compute the
following quantities:
1+3i
.
13i
ei/4 . Check the Eulers formula eix = cos x + i sin x by computing the right hand
side too, i.e. cos( 4 ) + i sin( 4 ).
Execute the command exp(/2 i) and exp(/2i). Can you explain the difference
between the two results?
13
2 6 0 0 0 0
3 9 0 0 0 0
0 0 1 2 0 0
G=
0 0 3 4 0 0
0 0 0 0 5 5
0 0 0 0 5 3
8. Manipulate a matrix: Do the following operations on matrix G created above in (6).
Delete the last row and last column of the matrix.
Extract the first 4 4 submatrix from G.
Replace G(5,5) with 4.
What do you get if you type G(13) and hit return? Can you explain how MATLAB
got that answer?
What happens if you type G(12,1) = 1 and hit return?
9. See the structure of a matrix: Create a 20 20 matrix with the command A =
ones(20). Now replace the 10 10 submatrix between rows 6:15 and columns 6:15 with
zeros. See the structure of the matrix in terms of non-zero entries with the command
spy(A). Set the 5 5 submatrices in the top right corner and bottom left corner to zeros
and see the structure again.
10. Create a symmetric matrix: Create an upper triangular matrix with the following
command:
A = diag(1 : 6) + diag(7 : 11, 1) + diag(12 : 15, 2)
Make sure you understand how this command works (see the online help on diag if
required). Enter triu(A,1), triu(A,2) and triu(A,-1) Can you guess the outputs? Now
use the upper off-diagonal terms of A to make A a symmetric matrix with the following
command:
A = A + triu(A, 1)0 .
11. The geometric series: The sum of a geometric series 1 + r + r2 + + rn approaches
1
for |r| < 1 as n . Create a vector n of 11 elements from 0 to 10. Take
the limit 1r
r = 0.5 and create another vector x = [r0 , r1 , , rn ] with the command x = r.n. Now
take the sum of this vector with the command S = sum(x)(S is the sum of the actual
1
and compare the computed sum S. Replace the procedure
series). Calculate the limit 1r
taking n from 0 to 50 and then from 0 to 100.
12. Solving Equations: The command solve(f(x)) solves an equation in one unknown
f (x) = 0. The command [x, y] = solve(f(x,y),g(x,y)) solves a system of equations
in two unknowns, f (x, y) = 0, g(x, y) = 0. The calculations are based on symbolic
calculations. The variables x, y, z, a, b, c are declared to be symbolic variables with the
command
14
>> syms x y z a b c
(a) Use solve command to find the solutions of the following equations:
(i) x2 5x + 6 = 0 (ii) x2 2x + 2 = 0 (iii) x3 x + 1 = 0
(iv) x3 2x 5
(v) xex = 1
Use > > double(ans) or > > eval(ans) in the ans you get in MATLAB output.
(b) Use solve command to solve the two equations simultaneously:
(i) y 4x2 + 3 = 0, x2 /4 + y 2 1 = 0 (ii) x2 y 2 = 3, x2 + y 2 = 13
(iii) x2 = 3xy 7, y = 2(x + 1)
15
0.7
Plotting
Helpful built-in-functions used in plotting: The figures can be given titles, axes labeled
and text placed within the figure with the following commands which take a string as argument.
title()
xlabel()
ylabel()
zlabel()
gtext()
text()
grid
figure title
x-axis label
y-axis label
z-axis label
place text on the graph using the mouse
position text as specified coordinates
grid lines on
Type
>> help legend
16
m
c
r
g
b
w
k
magenta cyan red green blue white black
Marker style: The followings are the marker style used in MATLAB.
Symbol
.
o
x
+
*
s
d
Style
point
circle
x-mark
plus
star
square
diamond
Symbol
<
>
p
h
Style
triangle triangle triangle triangle pentagram hexagram
down
up
left
right
Line style: The followings are the line styles used in MATLAB.
Symbol
Style
solid
:
.
dotted dash dot
dashed
Multiple Plot
The command plot creates linear x-y plots. If x and y are vectors of same length, the
command plot(x,y) opens a graphics window and draws an x y plot of the element of x
versus the ones of y, e.g.
>> x = -4:0.01:4; y = x.^2; plot(x,y);
analogously
>> s = -10:0.01:10; t = exp(-s.^2); plot(s,t);
By default, the plot command always opens figure(1) and overwrite the old graphics. If a
current graphics window (figure) should be kept, another one can be opened with the command
figure(2) or simply figure which then becomes the current figure where graphs from subsequent
plotting commands will be placed.
17
x = -2:0.01:2; y = x.^2;
s = -10:0.01:10; t = exp(-s.^2);
plot(x,y,s,t);
plot(x,y); hold on; plot(s,t); hold off;
For plotting specified line types, marker types and colors can be chosen, for example
>> plot(x,y,r--,s,t,b:+);
renders a red dashed line for the first graph and a blue dotted one for the second one where
additionally the nodes are marked by the symbol +.
Line width of the plotting can be chosen according to our choice, for example
>> plot(x,y,r--,s,t,b:,LineWidth,3);
The conventional plot is a linear plot. The followings are the combination of linear axes
with logarithmic axes:
The semilogx function plots x data on logarithmic axes and y data on linear axes.
The semilogy function plots x data on linear axes and y data on logarithmic axes.
The loglog function plots both x and y data on logarithmic axes.
Other speciliazed 2-D plotting functions that are worth to be explore via help are polar,
bar, pie, stem, stairs, hist etc.
polar(theta,r); stem(x,y); stairs(x,y); hist(x,y); bar(x,y) For vertical bar plot;
barh(x,y)For horizontal bar plot; pie(x); pie(x,explode) The operational array explode controls whether or not individual pie slices are seperated from the remainder of
the pie.
>>
>>
>>
>>
>>
x = [10 37 5 6 6];
explode = [0 1 0 0 0];
pie(x,explode);
title(\bfExample of a pie plot);
legend(One,Two,Three,Four,Five);
For visualizing 3-D graphics and generating animations: plot3(x,y,z) mesh(x,y,z) surf(x,y,z)
surfc(x,y,z) contour(x,y,z) etc. For example
>> x = linspace(-4,4,20); y = x; [X,Y] = meshgrid(x,y);
>> Z = exp(-0.5*(X.^2 + Y.^2)); mesh(X,Y,Z);
For mesh, surf, contour plotting create the meshgrid by using the command
[X,Y] = meshgrid(xstart:xincrement:xend, ystart:yincrement:yend)
18
There are several other plotting functions to produce plots if you are plotting a function:
fplot, ezplot, ezpolar, ezplot3, ezcontour, ezcontourf, ezsurf, ezsurfc etc. For
these try to use online help: > > help fplot etc. The inline function is used to introduce
the function f in these plots. Let us look the use of inline function to plot ezsurf.
>> f = inline(x*exp(-x^2-y^2));
>> ezsurf(f, [-pi,pi,-pi,pi])
Here [-pi,pi,-pi,pi] is [xmin,xmax, ymin, ymax].
inline function: The inline function is a kind of numerical function that is really used in
a short program that operates on numbers to produce numbers. Here is a simple example:
>> f = inline(x^3 + x -1)
f =
Inline function:
f(x) = x^3 + x -1
To evaluate f (x) = x3 + x 1 at x = 2, enter f (2). If we wish the function to be array
smart, we must write
>> f = inline(x.^3 + x -1);
>> A = [1 2 3;4 5 6];
>> B = f(A)
B =
1
67
9
129
29
221
Sublot:
The command subplot can be applied to partition the screen so that several small plots can
be placed in one figure.
Syntax:
subplot(m,n,p)
This command divides the current figure into m n equal sized regions, arranged in m rows
and n columns, and creates a set if axes at position p to recieve all plotting commands. The
subplots are numbered from left to right end from top to bottom. For example, the command
subplot(2,3,4) would divide the current figure into six regions arranged in two rows and three
columns, and create an axis in position 4 (the lower left one) to accept new plot data. The
following example will display the use of subplot.
>>
>>
>>
>>
>>
>>
figure(1)
subplot(2,3,1);
x = -pi:pi/20:pi; y = sin(x); plot(x,y);
subplot(2,3,5);
x = -pi:pi/20:pi; y = cos(x);plot(x,y);
title(Subplot 2 title);
19
MATLAB (Exercise - 3)
MATLAB Plotting
1. The distance travelled by a ball falling in the air is given by x = x0 + v0 t + 12 gt2 .Use
Matlabs plot command to plot t versus x for 0 x 3 when x0 = 10m, v0 = 15m/s
and g = 9.81 ms2 . Write the text Ball using the command gtext(Ball) in the figure
window.
2. Plot the functions y(t) = sin t and y(t) = cos t versus time in a single figure window for
2 t 2 where sin t versus time graph is shown by solid red line and cos t versus
time graph is shown by blue dashed line with a width of pixels 3. Dont forget to mention
labels, title and legends of the plots.
3. Plot y = e0.4x sin x, 0 x 4 taking 10, 50 and 100 points in the interval on the
same MATLAB figure window.
4. (a) Plot the function v(t) = 10 e(0.2+i)t for 0 t 10 using the function plot(t,v).
What is displayed on the plot?
(b) Plot the above function using the function plot(v). What is displayed on the plot
this time?
(c) Plot the real and imaginary parts of v(t) versus time in a single figure window where
real versus time graph is shown by solid blue line and imaginary versus time graph
is shown by red dashed line.
(d) Create a polar plot of the above function.
(e) Plot the above function using plot3, where the three dimensions to plot are the real
part of the function, the imaginary part of the function and time.
5. Plot the respective 3-D/2-D plots of the following functions:[Take online help]
(a) Plot mesh and meshc of the function z =
y 3. In the plotting command once use
>>
>>
>>
>>
>>
>>
>>
>>
xy(x2 y 2 )
x2 +y 2
in the range 3 x 3, 3
x = -3:.1:3;
y = x;
[X,Y] = meshgrid(x,y);
Z = X.*Y.*(X.^2 - Y.^2)./(X.^2 + Y.^2);
figure(1)
mesh(X,Y,Z);
figure(2)
meshc(X,Y,Z);
x = -3:.1:3;
y = x;
x = x + (x==0)*eps;
y = y + (y==0)*eps;
[X,Y] = meshgrid(x,y);
Z = X.*Y.*(X.^2 - Y.^2)./(X.^2 + Y.^2);
figure(1)
mesh(X,Y,Z);
20
>> figure(2)
>> meshc(X,Y,Z);
Handle the width of the curves in meshc( ) plot using the command:
h = meshc(X,Y,Z) and set(h,LineWidth,2). Try to understand the output in
the command window and figure window!
(b) Plot mesh and meshc of the function z = sin x + sin y in the range 3 x
3, 3 y 3.
x2 +y 2
4
(d) Plot the parametric curve x(t) = t, y(t) = e 2 sin t for 0 < t < /2 using ezplot.
ezplot and fplot command plots the function directly, without the necessity of
creating intermediate data array. Plot using fplot command.
(e) Plot the function f (x) =
sinx
x
(f) Plot the cardiod r() = 1 + cos() for 0 < < 2 using ezpolar.
(g) Plot the contours x2 + sin(xy) + y 2 = 0 using ezcontour over the domain /2 <
x < /2, /2 < y < /2.
(h) Create a surface plot with contours of the function H(x, y) =
< x < , 2 < y < 2.
2 y 2
x2
2
+ (1 cos y) for
(a) Use Matlabs contour command to plot 20 contours over the domain {(x, y) : 2
x, y 2}. Take on line help command .
(b) Use the form clabel(c,h,manual) to selectively label several contours with the
mouse.
(c) Use Matlabs contour3 command to plot twenty contours over the domain {(x, y) :
2 x, y 2}. Turn off the grid with the command grid off. Help: Type help
contour3 to obtain help on contour3 command.
(d) Use Matlabs meshc command to obtain a simultaneous plot of the surface and
the level curves of the function over the domain {(x, y) : 2 x, y 2}. Remove
hidden line with the command hidden off.
7. Do the same as in Exercise 6 for the function f (x, y) =
the domain {(x, y) : 2 x, y 2}.
3y
x2 +y 2 +1
8. (Plotting Complex data): Complex data has both real and imaginary components,
and plotting complex data with MATLAB is a bit different from plotting real data. For
example, consider the function
y(t) = e0.2t (cos t + i sin t)
If this function is plotted with the conventional plot command, only the real data will be
plotted the imaginary part will be ignored. In this plot you will get a warning message
that the imaginary part of the data is being ignored. Consider the t as t = 0 : pi/20 : 4.
Then
(a) Plot the function y(t) using the conventional plot comman plot(t,y) with lineWidth
3. Dont forget to mention labels and title of the plot.
21
(b) Plot the real and imaginary parts of y(t) versus time in a single figure where real
VS time graph is shown by red-dashed. Mention the respective legends.
(c) Plot real VS imaginary parts of y(t).
(d) Polar plot for angle of y(t) VS absolute value of y(t). Helpful built-in-functions:
real(), imag(), abs(), angle(), hold on
9. Thermodynamics(The ideal gas law): An ideal gas is one in which all collisions
between molecules are perfectly elastic. It is possible to think of the molecules in an ideal
gas as perfectly hard billiard balls that collide and bounce off of each other without losing
kinetic energy.
Such a gas can be characterized by three quantities: absolute pressure (P), volume (V)
and absolute temperature (T). The relationship among these quantities in an ideal gas is
known as the ideal gas low:
P V = nRT
where P is the pressure of the gas in kilopascals(Kpa), V is the volume of the gas in litres
(L), n is the number of molecules of the gas in units of moles(mol), R is the universal gas
constant (8.314 L Kpa/mol K), and T is the absolute temperature in kelvins (K).(Note:
1 mol = 6.023 1023 molecules.)
(a) Assume that a sample of an ideal gas contains 1 mole of molecules at a temperature
of 273K, and answer the following questions:
i. How does the volume of this gas vary as its pressure varies from 1 to 1000 Kpa?
Plot pressure versus volume for this gas on an appropriate set of axes (linear,
semilog etc?). Use a solid red line with a width of 3 pixels.
ii. Suppose that the temperature of the gas is increased to 373 K. How does the
volume of this gas vary with pressure now? Plot pressure versus volume for this
gas on the same set of axes as part (i). Use a dashed blue line with a width of
2 pixels.
(b) Assume that the volulme of 1 mole of this gas is 101, and plot the pressure of the gas
as a function of temperature as the temperature changed from 250 to 450 Kelvins.
What sort of plot is most appropriate for this data?
22
0.8
input function:
The input function displays a prompt string in the command window and then waits for
the user to type in a response. For example, consider the following statements:
my_val = input(Enter the input value: );
If the input function includes the character s as a second argument, then the input data is
returned to the user as a character string. Thus, the statement
>> in1 = input(Enter data: );
Enter data: 1.34
stores the value 1.34 into in1, while the statement
>> in2 = input(Enter data: , s);
Enter data: 1.34
stores the character string 1.34 into in2.
disp function:
The disp function displays the data. The disp function accepts an array argument, and
displays the value of the array in the command window. If the array is of type char, then
character string contained in the array is printed out.
This function is often combined with the functions num2str (converts a number to string)
and int2str (converts an integer to string) to create message to be displayed in the command
window. For example, the following MATLAB statements
>> str = [The value of pi = num2str(pi)];
>> disp(str);
will display The value of pi = 3.1416 in the command window. The first statement creates
a string array containing the message, and the second statement displays the message.
fprintf function:
An even more flexible way to display data is with the fprintf function. The fprintf function
displays one or more values together with related text and lets the programmer control the way
the displayed values appear. The general form of this function when it is used to print to the
command window is
fprintf(format, data)
where format is a string describing the way the data is to be printed, and data is one or more
scalars or arrays to be printed. The format is a character string containing text to be printed
plus special characters describing the format of the data. For example, the function
fprintf(The value of pi is %f \ n , pi)
23
Format string
Results
%d
display value as an integer
%e
display value in exponential format
%f
display value in floating format
%g
display value in either floating format or
exponential format, whichever is shorter
\n
skip to new line
will print out The value of pi is 3.141593 followed by a line feed. The character %f is a
conversion character. It indicates that the value in the data list should be printed out in
floating point format at that location in the format string. The character \ n is an escape
character. It indicates that a line feed should be issued so that the following text starts on a
new line. Other characters are as shown in table below.
fprintf(The value of pi is %8.2f \ n , pi)
will print out The value of pi is
3.14 followed by a line feed. The conversion %8.2f
indicates that the first data item in the function should be printed out in floating point format
in a field eight characters wide, including two digits after the decimal point.
Its limitation: It displays only the real portion of a complex value.
>>
>>
>>
>>
x = 2 + 3*i;
str = [disp: x = num2str(x)];
disp(str);
fprintf(fprintf: x = %8.4f \n , x);
0.9
M-files
MATLAB has two M-files. They are script files and function files.
Both are called M-files, because they have a file extension of .m.
Where to type? Select new M-file from the file menu. A new edit window will appear.
Type M-files in this window.
Scripts files:
A script file is a user-created file with a sequence of MATLAB command in it. It is
equivalent to typing all the commands stored in the script file, one by one, at the MATLAB
prompt in the command window.
The file must be saved with a .m extension to its name, thereby, making it an M-file.
The file name must begin with a letter and the rest of the character may include digits
and underscores but not period other than the last one .m.
24
The script file can execute by typing its name (without the .m extension)in the command window.
Script files work on global variables, that is, variables currently present in the workspace.
Results obtained from executing script files are left in the workspace.
Script files are useful when we have to repeat a set of commands several times.
Script files may be used to enter a data into huge matrices, since entry error can be easily
corrected.
Example 6 Write a script file to draw a unit circle whose parametric equation is given by
x = cos(), y = sin (), 0 2
Solution steps:
Select New M-file from the file menu. A new edit window will appear.
Type the following lines into this edit window. Lines starting with % sign are interpreted
as comment line by MATLAB and are ignored.
% Script file: circle.m
%
% Purpose:
%
This program plots the unit circle.
%
% File written to give idea to students how to creat a script file.
% Dated on Feb 14, 2011.
%
% Define Variables:
%
theta
--- angle in radian.
%
x
--- x = cos(theta).
%
y
--- y = sin(theta).
%-------------------------------------------------------------------------% Create array for input variables
theta = linspace(0, 2*pi, 100); % creat vector data
x = cos(theta);
% generates x - coordinates
y = sin(theta);
% generates y - coordinates
% Creates plot
plot(x,y);
axis(equal);
title(Circle of unit radius);
text(0.5,0.5,note this);
%
%
%
%
Select save as from file menu. A diaglog box will appear. Type the name of the document
as circle.m in the folder you want to be. Then click yes to save the file.
Now to get back to MATLAB type the following in the command window.
25
y = r*sin(theta);
%
plot(x,y,LineWidth,3);
%
axis(equal);
%
title([Circle of radius r = , num2str(r)]);%
%
generates y - coordinates
Plot the circle with 3 pixels
set equal scale on axes
put the title with the
value of r
Select save as from file menu. A diaglog box will appear. Type the name of the document
as circlefn.m in the folder you want to be. Then click yes to save the file.
Now to get back to MATLAB type the following in the command window.
>> help circlefn
>> circlefn(3)
This will display the circle of radius 3 having pixels 3.
27
MATLAB (Exercise - 4)
MATLAB Functions
1. Show the center of the circle: Modify the script file circle.m of the example 6 to
show the center of the circle on the plot, too. Show the center point with red color having
marker type +.
2. Change the radius of the circle: Modify the script file circle.m created above in (1)
to draw a circle of arbitrary radius r as follows:
Include the following command in the script file before the first executable line (theta
...) to ask the user to input (r) on the screen:
r = input(Enter the radius of the circle: )
Modify the x and y coordinate calculations appropriately.
Save and execute the file. When asked, enter a value for the radius and press return.
3. Temperature Conversion: Celsius (C), Fahrenheit (F), Reaumur (R), Kelvin (K) and
Rankine (Ra) are five scales of measurement of temperature. Each scale of temperature
has an upper fixed point (boiling point of water) and a lower fixed point (melting point
of ice). The difference between these fixed points is called Fundamental units, which is
100 for Celsius, 180 for Fahrenheit, 80 for Reaumur, 100 for Kelvin and 180 for Rankine.
The relation between the scale is
F 32
R0
K 273
Ra 492
C 0
=
=
=
=
100
180
80
100
180
(a) Design a MATLAB program that reads an input temperature in degree Fahrenheit,
converts it to an absolute temperature in Kelvin, and write out the result. To do
this
i. Input the following command to ask user to input the temperature in Fahrenheit
in screen:
temp_f = input(Enter the temperature in degree Fahrenheit: );
ii. Convert to Kelvins using
temp_k = (5/9)*(temp_f - 32) + 273;
iii. Write out the result using
fprintf(%6.2f degree Fahrenheit = %6.2f kelvins \n,...
temp_f, temp_k);
(b) Write a function that outputs a conversion table for Celsius and Fahrenheit temperatures for 1 degree increment in Celsius between two temperatures ti and tf in
celsius. For conversion table use the command temp table = [C,F], where C =
[ti : tf ] and F = (9/5)*C + 32, and output will be named temp table.
4. Statistical Evaluation of data: If all of the input values are available in an array
(vector), the mean and standard deviation of a set of numbers can be calculated by
MATLAB function mean() and std() respectively. The average mean of a q
set of numbers
PN
i
is defined by X = i=1
and the standard deviation is defined by =
N
Now follow the following steps:
PN
2
i=1 (Xi X)
5. Roots of Quadratic Equations: Write a program that will solve for the roots of a
quadratic equation, whether they are distinct real roots, repeated real roots or complex
roots, without requiring test on the value of the discriminate.
Test the program using real input data from the following quadratic equations.
x2 + 5x + 6 = 0 Roots are: -2, -3
x2 + 4x + 4 = 0 Roots are: -2, -2
x2 + 2x + 5 = 0 Roots are: -1+2i, -1-2i
29
0.10
Branches and Loops both are MATLAB construct that permit us to execute a sequence of
statements under user control. The syntax for bracnching statements is if-elseif-else and that
for control-flow statements are for -loops and while-loops. In addition, MATLAB provides
switch, try/catch, break, error, and return to control the execution of scripts and functions. A description of these functions follows.
Branches
Branches are MATLAB statements that permit us to select and execute specific selection of
code (called blocks) while skipping other section of codes. They are variations of if construct,
the switch construct, and the try/catch construct.
The if construct
The if construct has the form
if control_expr_1
Block 1 statements
elseif contro_exp_2
Block 2 statements
elseif contro_exp_3
Block 3 statements
......
.................
else
Block n statements
end
where the control expressions are logical expressions that control the operation of the if construct.
Note that there can be any number of elseif clauses in an if construct, but there can be at
most one else clause.
Nested if Construct
The if construct is very flexible. It must have one if statements and one end statement. In
between, it can have any number of elseif clauses, and may also have one else clause. With
this combination, it is possible to implement any desired branching construct.
In addition, if constructs may be nested. Two if constructs are said to be nested if one
of them lies entirely within a single code block of the other one. Thus the nested if construct
has the form
....
if (Test 1)
...
if (Test 2)
...
if (Test 3)
30
...
end
...
end
...
end
Example 8 (Assigning letter grades) Suppose that we are writing a program that reads in
a numerical grade and assigns a letter grade to it according to the following table: Write an if
95 <
86 <
76 <
66 <
0<
grade
grade 95
grade 86
grade 76
grade 66
A
B
C
D
F
construct that will assign the grades as described above using (a) multiple elseif clauses and
(b) nested if constructs.
Solution
(a) One possible structure using elseif clauses is:
if grade > 95
disp(The
elseif grade > 86
disp(The
elseif grade > 76
disp(The
elseif grade > 66
disp(The
else
disp(The
end
grade is A. );
grade is B. );
grade is C. );
grade is D. );
grade is F. );
end
end
end
The switch construct
The switch construct is another form of branching construct. It permits a programmer to
select a particular code block to execute based on the value of a single integer, character, or
logical expression. The general form of switch construct is:
switch (switch_expr)
case (case_expr_1)
Block 1 statements
case (case_expr_2)
Block 2 statements
........
otherwise
Block n statements
end
If many values of the switch expr cause the same code to execute, all of those values may
be included in a single block by enclosing them in brackets, as shown below. If the switch
expression matches any of the case expressions in the list, then the block will be executed.
switch (switch_expr)
case (case_expr_1, case_expr_2, case_expr_3)
Block 1 statements
case (case_expr_4, case_expr_5)
Block 2 statements
........
otherwise
Block n statements
end
Example 9 (Integer between 1 and 10 is even or odd:) The following MATLAB program
determines whether an integer between 1 and 10 is even or odd, and print out an appropriate
message. It illustrates the use of a list of values as case selectors, and also the use of the
otherwise block.
Solution:
% EVEN_ODD --- This script file determines whether an integer between 1
% and 10 is even or odd, and points out an appropriate message. It
% illustrates the use of a list of values as case selectors, and also the
% of the otherwise block.
% ------------------------------------------------------------------------% File name: even_odd.m
value = input(Enter the integer:);
switch value
case {1,3,5,7,9}
disp(The integer is odd.);
case {2,4,6,8,10}
32
In (a) the control expression generates a 1 10 array, so statement 1 through n will be executed
10 times. The loop index i will be 1 on the first time, 2 on the second time, and so on. The
loop index will be 10 on the last pass through the statements. When control is returned to
the for statement after the tenth pass, there are no more columns in the control expression, so
execution transfers to the first statement after the end statement. Note that the loop index i
is still set to 10 after the loop finishes executing.
Control expression in (b) generates 1 5 array.
Control expression in (c) generates 1 3 array.
Control expression in (d) generates 2 3 array.
Example 11 (The factorial function:) The factorial function is defined as
n! = 1, n < 0
n! = n(n 1)(n 2) 3.2.1, n > 0
The MATLAB code to calculate n factorial for positive value of n would be
34
n_factorial = 1
for i = 1:n
n_factorial = n_factorial*i
end
Nested for loop
It is possible for one loop to be completely inside another loop. If one loop is completely
inside another one, the two loops are called nested loop. The following example shows the
two nested for loops used to calculate and write out the product of two integers.
for i = 1:3
for j = 1:3
product = i*j;
fprintf(%d*%d = %d\n, i, j, product);
end
end
The output is
1*1
1*2
1*3
2*1
2*2
2*3
3*1
3*2
3*3
=
=
=
=
=
=
=
=
=
1
2
3
2
4
6
3
6
9
Break
The command break inside a for or while loop terminates the execution of the loop, even
if the condition for execution of the loop is true. An example for break statement in a for
loop is shown below:
% file name--text_break in script file.
for i = 1:6
if i == 3;
break;
end
fprintf(i = %d\n,i);
end
disp([End of LOOP!]);
When this program is executed, the output is:
>> test_break
i = 1
i = 2
End of LOOP!
35
Continue
If a continue statement is executed in the body of a loop, the execution of the current
pass through the loop will stop and control will return to the top of the loop. The controlling
variable in the for loop will take on its next value, and the loop will be executed again. An
example to the continue statement in a for loop in shown below:
for i = 1:5
if i == 3
continue;
end
fprintf(i = %d \n,i);
end
disp([End of loop!]);
When this program is executed, the output is:
i =
i =
i =
i =
End
1
2
4
5
of loop!
Note that the continue statement was executed on the iteration when i was 3, and control
transferred to the top of the loop without executing the fprintf statement. The break and
continue statements work with both while and for loops.
Nested Break
for i = 1:3
for j = 1:3
if j == 3
break;
end
product = i*j;
fprintf(%d*%d = %d\n, i, j, product);
end
fprintf(End of inner loop \n);
end
fprintf(End of outer loop \n);
If the inner loop counter j is equal to 3, then the break statement will be executed. This
will cause the program to exit the innermost loop. The program will print out End of inner
loop, the index of the outer loop will be increased by 1, and execution of the innermost loop
will start over. The resulting output values are:
1*1
1*2
End
2*1
2*2
= 1
= 2
of inner loop
= 2
= 4
36
End
3*1
3*2
End
End
of inner loop
= 3
= 6
of inner loop
of outer loop
Error
The command error(message) inside a function or script aborts the execution, displays
the error message message, and returns the control to the keyboard.
37
MATLAB (Exercise - 5)
MATLAB Branches and Loops
1. Examine the following for loops and determine how many times each loop will be executed.
a. for i = 7:10 b. for i = 7:-1:10 c. for i = 1:10:10 d. for i = -10:3:-7
2. Examine the following loops and determine the value of res at the end of each of the
loops.
3.
a.
res = 0;
for i = 1:10
res = res +1;
end
b.
res = 0;
for i = 1:10
res = res + i;
end
c.
res(1) = 0;
for i = 1:10
res(i+1) = res(i) + i;
end
d.
res = 0;
for index1 = 1:10
for index2 = index1:10
if index2 ==6
break;
end
res = res + 1;
end
end
e.
res = 0;
for index1 = 1:10
for index2 = index1:10
if index2 == 6
continue;
end
res = res + 1;
end
end
38
a = 1;
n = 1;
while a < 100
a = a*n
n = n + 1
end
What values will the following MATLAB code print ?
a = 4;
b = 1;
n = 1;
while n <= 10
b = b + a^n/factorial(n);
n = n + 1;
end
4.
39
n = 10;
for i = 1:n
for j = 1:n
a(i,j) = 1/(i+j-1);
end
end
What value will the following program print ?
count = 0;
for d = 1:5
for m = 1:4
count = count + 1;
end
end
count
What value will the following program print ?
count = 0;
for d = 1:7
for h = 1:24
for m = 1:60
for s = 1:60
count = count + 1;
end
end
end
end
count
5.
40
b = 3;
b
-1
a > b
2;
41
For what values of the variable a will the following MATLAB code print Hello
World ?
if a < 8 || a >= 2
disp(Hello World)
else
disp(Goodbye World)
end
What does this code do ?
for i = 1:10
if (i > j)&( rem(i,2) == 0 )
x(i) = 1;
else
x(i) = 0;
end
end
What does this code do ?
n = 10;
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
6. Do some cool operations: Create a 10 10 random matrix with the command A =
rand(10). Now do the following operations:
Multiply all elements by 100 and then round off all elements of the matrix to integers
with the commnad A = fix(A).
Replace all elements of A < 10 with zeros. [Help: [r,c] = find(A < 10) returns the
row and column indices i and j of A, in vector r and c, for which Aij < 10]
Replace all elements of A > 90 with infinity (inf).
Extract all 30 aij 50 in a vector b, that is, find all element of A that are between
30 and 50 and put them in a vector b.
42
MATLAB (Exercise - 6)
MATLAB Programs
1. Write a program for the sum of first n natural numbers.
2. Write a program for the sum of first n odd positive integers.
3. Write a program for the sum of first n even positive integers.
4. Write a program to display an integer is even or odd.
5. Use for loop to perform the calculation of the values of y(k), where y(k) =
x = 1.5 and k = 1, 2, , 10.
xn
1 n2 ,
Pk
for
1
6. Write a MATLAB program to evaluate the function y(x) = ln 1x
for any user-specified
value of x, where x is number x < 1.0. Use an if construct to verify that the value passed
to the program is legal. If the value of x is legal, calculate y(x). If not, write a suitable
error message and quit.
7. Write a program that allows a user to enter a string containing a day of the week (sunday,
Monday, Tuesday etc.) and uses that a switch construct to convert the day to its
corresponding number, where Sunday is considered the first day of the week and Saturday
is considered the last day of the week. Print out the resulting day number. Also, be sure
to handle the case of an illegal day name! (Note: Be sure to use the s option on function
input so that the input is treated as a string)
8. Write an M-file to evaluate the equation y(x) = x2 3x + 2 = 0 for all values of x between
-1 and 3 in steps of 0.1. Use a for loop to perform the calculation. Plot the resulting
function using a 3-point-thick dahsed red line.
9. Write an M-file to calculate the factorial function N !. Be sure to handle the special case
of 0!. Also, be sure to report an error if N is negative or not an integer.
10. Fibonacci Numbers: The nth Fibonacci number is defined by following recursive equation:
f (1) = 1, f (2) = 2, f (x) = f (x 1) + f (x 2)
Therefore f (3) = f (2) + f (1) = 2 + 1 = 3, and so forth for higher numbers. Write an
M-file to calculate and write out the nth Fibonacci number for n > 2, where n is input
by the user. Use a while loop to perform the calculation.
11. Write a function with input parameters x and n that evaluates the nth order Taylor
approximation of ex . Write a Script that calls the function for various values of n and
plot the error in the approximation.
12. For the up-down sequence
xk+1 =
xk /2
3xk + 1
if xk = even
if xk = odd
x0 is given. Write a Script that builds up-down sequence while x(k) = 1 and k 200
using the while statement. Plot the solution vector x(k), k = 1, , 200 for several initial
conditions.
43
f (x0 )
f 0 (x0 )
Step 3: Follow the above procedure to find successive approximations xn+1 using the
recursive formula
f (xn )
,
n = 1, 2, 3,
xn+1 = xn 0
f (xn )
Step 4: Stop when
|xn xn1 | <
where is the prescribed accuracy.
5. Algorithm for Iteration Method
Step 1: Express f (x) = 0 as x = (x) such that
|0 (x)| < 1
Step 2: Choose a trial function x0 .
Step 3: Find first approximation x1 using
x1 = (x0 )
Step 4: Follow the above procedure to find successive approximations xn+1 using the
recursive formula
xn+1 = (xn ),
n = 0, 1, 2,
Step 5: Stop when
|xn xn1 | <
where is the prescribed accuracy.
6. Algorithm for Newton Raphsom Method for system of nonlinear equations
Step 1: Choose the initial approximate row vector X0 for the system of equations
f (x, y) = 0 and g(x, y) = 0
Step 2: Compute Jacobian J(f, g) at X0 and F (X0 ) = [f (X0 )
Step 3: Solve the 2 2 nonlinear system of equations
g(X0 )]0
7. Algorithm for Fixed Point Iteration Method for system of nonlinear equations
Step 1: Choose the initial approximate row vector X0 for the system of equations
f (x, y) = 0 and g(x, y) = 0
Step 2: Express f (x, y) = 0 as x = F (x, y) and g(x, y) = 0 as y = G(x, y) such that
|
F
G
G
F
|+|
| < 1 and |
|+|
|<1
x
y
x
y
46