The aim of this slide to study the Matlab about Engineering , Science and Mathematics Computation,MATLAB stands for Matrix Laboratory. MATLAB is a high-performance language for
technical computing Software" package, Math,Numeric/symbolic and computation Algorithm development (optimized for Digital Signal Processing)Scientific , engineering calculations and graphics. Data analysis, exploration, and visualization,Data acquisition Modeling,Simulation, and prototyping, Application development, including graphical user interface building.
Play hard learn harder: The Serious Business of Play
Introduction to Matlab for Engineering Students.pdf
1. An Introduction to Matlab for
Engineers and Scientist
DR. AZIZUL HASAN
DEPT. OF MATHEMATICS
JAZAN UNIVERSITY JAZAN
1
DR.AZIZUL HASAN
2. Outline:
What is Matlab?
Matlab Screen
Variables, array, matrix, indexing
Operators (Arithmetic, relational, logical )
Display Facilities
Flow Control
Using of M-File
Writing User Defined Functions
Conclusion
2
DR.AZIZUL HASAN
3. 3
1. INTRODUCTION:
The name MATLAB stands for Matrix Laboratory. The basic
building block of MATLAB is the matrix. It is not confined
to the solution of Matrix related problems. With its inbuilt
functions, it is an excellent tool for linear algebraic
computations, data analysis, signal processing, optimization,
numerical solutions of ordinary differential equations (ODE),
quadrature, 2D & 3D, graphics and many other types of
scientific computation. Therefore, we can say: MATLAB is a
software package in high performance language for technical
computing. It integrates computation, visualization and
programming in an easy to use environment where problems
and solutions are expressed in familiar mathematical
notation.
DR.AZIZUL HASAN
4. MATLAB stands for Matrix Laboratory.
MATLAB is a high-performance language for
technical computing Software" package .
Math,Numeric/symbolic and computation
Algorithm development (optimized for Digital Signal
Processing)
Scientific , engineering calculations and graphics
Data analysis, exploration, and visualization
Data acquisition Modeling
Simulation, and prototyping
Application development, including graphical user interface
building
What is MATLAB?
4
DR.AZIZUL HASAN
5. Why Learn and Use MATLAB?
Heavily used in Computational Mathematics/EE/CE
courses with DSP content (CE316, EET316)
Extensive built-in commands for scientific and
engineering mathematics
Easy way to generate class demonstrations and test
examples
Simple and intuitive programming for more complex
problems
Standard and widely-used computational environment
with many features, extensions, and links to other
software.
5
DR.AZIZUL HASAN
6. • In Windows
systems
MATLAB is
started by
double-clicking
the mouse on the
appropriate icon.
6
DR.AZIZUL HASAN
7. Once MATLAB is running the GUI (Graphical User
Interface) will appear Default Window appearance
7
DR.AZIZUL HASAN
8. Matlab Screen
Command Window
type commands
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
view past commands
save a whole session
using diary
8
DR.AZIZUL HASAN
9. What are we interested in?
• Matlab is too broad for our purposes in this
course.
• The features we are going to require is
Matlab
Command
Line
m-files
functions
mat-files
Command execution
like DOS command
window
Series of Matlab
commands
Input
Output
capability
Data
storage/
loading
9
DR.AZIZUL HASAN
10. 10
BASICS:
2.1 MATLAB WINDOWS: There are three basic window which are as follows:
1. MATLAB DESKTOP: This is the window which appears by default when
MATLAB is launched. It consists of :
COMMAND WINDOW: This is the main window , where command are written.
It is characterized by MATLAB command prompt (>>). The results also appear on this
window(except figures, which appear on figure window) which command is written.
Commands cannot be edited in this window.
CURRENT DIRECTORY: This appears on the bottom left side of MATLAB
desktop. It is where all files are listed. With a mouse right click, you can run M-files,
rename, delete them etc after selecting a file from here.
WORKSPACE: This sub-window shows all the variables generated so far and also
shows their type and size.
COMMAND HISTORY: All commands typed on the MATLAB prompt are
recorded here. Also commands can be selected from here and create as M-file. Thus it
remains records of MATLAB functions run
DR.AZIZUL HASAN
11. 11
2. FIGURE WINDOW:
The output of all the commands written on the command
window or executed by writing in M-file, whose output is a
graph , appears on the window. The user can create as many
figure windows as the system memory allows. A figure
window is showing sine curve is shown in figure.
3. EDITOR WINDOW:
This is where we can write, create, edit and save programs in
a file. The file is known as M-file. To select editor window,
go to file and then select M-file. The programs written on the
file are first saved and then run to get the results. To save and
run the program, go to debug and select „save and run‟. The
result appear on the command window. The figure appear on
the figure window. A editor window is shown as in figure:
DR.AZIZUL HASAN
12. 12
2.2 LANGUAGES:
MATLAB is a high-level language that includes matrix-based data structures,
its own internal data types, an extensive catalog of functions and scripts, the
ability to import and export to many types of data files, object-oriented
programming capabilities, and interfaces to external technologies such as
COM, Java, program written in C and Fortran, and serial port devices.
2.3 INPUT-OUTPUT:
MATLAB takes input from the screen and rushes output to the screen i.e. it
supports interactive computation. It can read input files and write output files.
2.3.1 Data Type: There is no need to declare a data to be real or complex.
When a real number is entered as a variable, MATLAB automatically sets the
variable to be real. Fundamental data type is the array
2.3.2 Dimension: Dimension state is not required in the MATLAB. It is
automatic.
2.3.3 Case Sensitivity: It differentiates between lower and upper cases.
It is case sensitive.
2.3.4 Output Display: The output of every command appears on the
screen unless MATLAB is directed otherwise. A semi-colon(;) suppress the
output when used at the end of a command except for the graphics.
DR.AZIZUL HASAN
13. 13
2.4 GETTING STARTED
2.4.1 STARTING MATLAB: On windows platform, start MATLAB by
double clicking the MATLAB shortcut icon on your Windows desktop.
2.4.2 WRITING COMMAND: When you start MATLAB, the MATLAB
desktop appears containing tools for managing files, variables, and
applications associated with MATLAB. You can start writing your command
at the prompt appears on command Window. You can also write command in
M-file.
2.4.3 PRINTING GRAPHICS: The simplest way to get print out of the
graph is to type print command window after the graph appears in the figure
window. Alternatively activate the figure window and then select print from
the file menu.
2.4.4 QUITTING MATLAB: To end your MATLAB session, select file
>Exit MATLAB in the desktop or type quit in the command window. You
can run a script file named finish.m each time MATLAB quits that, for
example, executes function to save the workplace, or display a quit
confirmation dialog box
DR.AZIZUL HASAN
14. 14
3. ACCESSORIES
3.1 TOOLBOXES: MATLAB features a family of add-on-application
specific solutions called toolboxes. Very important to most users of
MATLAB, toolboxes allow you to learn and apply specialized technology.
Toolboxes are comprehensive collections of MATLAB environment to
solve particular classes of problems. Areas in which
toolboxes are available include signal processing, control systems, neural
networks, fuzzy logic, wavelets, simulation, and many others. There are 78
toolboxes available. Thus we can say MATLAB basically works as a
platform and for solving a particular problem, concerned toolbox is
required. Few of the toolboxes are as follows:
Communication toolbox ,Control system toolbox ,Curve fitting toolbox
Data acquisition toolbox ,Filter design toolbox ,Fuzzy logic toolbox
Instrument control toolbox ,Optimization toolbox ,Statistics toolbox
Symbolic maths toolbox, etc.
DR.AZIZUL HASAN
15. 15
3.2 SIMULINK: Simulink is a software package that enables you to
model, simulate, and analyze systems whose outputs change over time.
Such system are often referred to as dynamic systems. Simulink can be
used to explore the behavior of a wide range of real- world dynamic
systems, including electrical circuits, shock absorbers, braking systems,
and many other electrical, mechanical,
and thermodynamic system. This section explains how Simulink works.
Simulating a dynamic system is a two step process with Simulink. First, a
user creates a block diagram, using a block diagram Simulink model
editor that graphically depicts time dependent mathematical relationship
among the system‟s inputs, states, and outputs. The user then commands
simulink to simulate the system represented by the model from a
specified start time to a specified stop time.
DR.AZIZUL HASAN
16. MATLAB symbols
>> prompt
. . . continue statement on next line
, separate statements or variables and out put data,
separate the row and column indices in a matrix
separate the different commands on the same line
% start comment which ends at end of line
; (1) suppress the matlab output of a command
(2) separate rows in the input list of a matrix
: A colon is used to specify range in creating vectors, for
matrix and vector indices, for loops
, A single right quote is used to transpose a vector or a matrix
16
DR.AZIZUL HASAN
17. MATLAB Variable Names
ans Default variable name for results
pi Value of
eps Smallest incremental number
inf Infinity
NaN Not a number e.g. 0/0
i and j i = j = square root of -1
realmin The smallest usable positive real number
realmax The largest usable positive real number
17
DR.AZIZUL HASAN
18. Variables (continued …)
• View variable contents by simply typing the variable
name at the command prompt
>> a =12
a =
1 2
>> a*2
a =
24
>>b=10;
>> c=a+b
c =
22
>>
Matlab
prompt
assign
operator
suppress
command
output
18
DR.AZIZUL HASAN
19. MATLAB Math & Assignment Operators
Power ^ or .^ a^b or a.^b
Multiplication * or .* a*b or a.*b
Division / or ./ a/b or a./b
or or . ba or b.a
NOTE: 56/8 = 856
- (unary) + (unary)
Addition + a + b
Subtraction - a - b
Assignment = a = b (assign b to a)
19
DR.AZIZUL HASAN
21. Priority rules
• Precedence is the order operations are
preformed, remember PEMDAS
• >> ((2+5)^2+2*2-10/5) innermost parentheses
is done first
– 7^2 exponentiation is next
– 2*2 or 10/5 multiplication or division next
– (49 + 4 – 2) addition or subtraction next
• Operations are done from left to right
final result gives 51
21
DR.AZIZUL HASAN
22. The : operator
• VERY important operator in Matlab
• Means ‘to’
>> 1:10
ans =
1 2 3 4 5 6 7 8 9 10
>> 1:2:10
ans =
1 3 5 7 9
22
DR.AZIZUL HASAN
23. Matlab help commands
• help
>> help whos % displays documentation for the function whos
>> lookfor convert % displays functions with convert in the first help
line
• Start Matlab help documentation
>> helpdesk
>>help function name
>>lookfor keyword
23
DR.AZIZUL HASAN
24. MATLAB Matrices
• MATLAB treats all variables as matrices. For our purposes
a matrix can be thought of as an array, in fact, that is how it
is stored.
• Vectors are special forms of matrices and contain only one
row OR one column.
• Scalars are matrices with only one row AND one column
24
DR.AZIZUL HASAN
25. MATLAB Matrices
• A matrix can be created in MATLAB as follows (note the
commas or space AND semicolons):
• Don‟t need to initialise type, or dimensions
>>A = [3 2 1; 5 1 0; 2 1 7]
A =
3 2 1
5 1 0
2 1 7
>>
semicolon for next row in matrix
square brackets to define matrices
25
DR.AZIZUL HASAN
26. Long Array, Matrix
• t =1:10
t =
1 2 3 4 5 6 7 8 9 10
• k =2:-0.5:-1
k =
2 1.5 1 0.5 0 -0.5 -1
• B = [1:4; 5:8]
x =
1 2 3 4
5 6 7 8
26
DR.AZIZUL HASAN
27. Generating Vectors from functions
• zeros(M,N) MxN matrix of zeros
• ones(M,N) MxN matrix of ones
• rand(M,N) MxN matrix of uniformly
distributed
random
numbers on (0,1)
x = zeros(1,3)
x =
0 0 0
x = ones(1,3)
x =
1 1 1
x = rand(1,3)
x =
0.9501 0.2311 0.6068
27
DR.AZIZUL HASAN
28. Matrix Index
• The matrix indices begin from 1 (not 0 (as in C))
• The matrix indices must be positive integer
A(-2), A(0)
Error: ??? Subscript indices must either be real positive integers or logicals.
A(4,2)
Error: ??? Index exceeds matrix dimensions.
28
DR.AZIZUL HASAN
30. The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2 1]
A =
1 2 3
5 1 4
3 2 -1
x = A(1,:)
x=
1 2 3
y = A(3 ,:)
y=
3 4 -1
b = x .* y
b=
3 8 -3
c = x . / y
c=
0.33 0.5 -3
d = x .^2
d=
1 4 9
K= x^2
Erorr:
??? Error using ==> mpower Matrix must be square.
B=x*y
Erorr:
??? Error using ==> mtimes Inner matrix dimensions must agree.
30
DR.AZIZUL HASAN
31. • Some characters are reserved by MATLAB for various purposes. Some as
arithmetic or matrix operators: =, +, - , *, / , and others are used to perform a
multitude of operations. Reserved characters cannot be used in variable or
function names.
• >> % anything after % until the end of line is treated as comments
>>
• >> a = 3 % define a to have the value 3
a =
3
• >> a = 3; % “;” suppresses printing
>>
• >> b = 4; c = 5; % “;” enables multiple commands on same line
>>
• >> d = 6, e = 7; % “,” delimits commands but enables printing
d =
Reserved Characters % = ; ,
If you include “;” at the
end of each statement,
result will not be shown
immediately
31
DR.AZIZUL HASAN
32. Reserved Characters : [ ] ( )
• >> x = 1:2:9 % define vector x with : operator (begin:interval:end)
x =
1 3 5 7 9
• >> y = 3:5 % interval is defaulted to 1; same as y=[3:5]
y =
3 4 5
• >> X = [1, 2, 3; 4, 5, 6] % 2D array. The ; is vertical concatenation.
% [ ] for arrays. Prevents ambiguity
% ; concatenates vertically (new row)
% , concatenates horizontally (new columns)
X =
1 2 3
4 5 6
• >> X(2,3) % ( ) for subscripting; why ans ?
ans =
6
32
DR.AZIZUL HASAN
33. Reserved Characters … and '
>> x = [1 2 3 … % elipses … means to be continued on the next line
4 5 6]
x =
1 2 3 4 5 6
>> s = 'this is a character string'; % blanks preserved within quotes
>> x = [1 2 3]' % ' performs transpose (e.g., turns row into column)
x =
1
2
3
>> X = [1 2 3; 4 5 6]; size(X) % figure out the size (dimensions) of X
ans =
2 3
>> X = [1 2 3; 4 5 6]; numel(X) % total number of entries in X
ans =
6
33
DR.AZIZUL HASAN
34. Array operations (continued)
>> a = 1:3; % a is a row vector
>> b = 4:6; % b is a row vector
>> c = a + b % a & b must agree in shape & size; c has same shape
5 7 9
>> A = [a;b] % combines rows to generate 2x3 matrix A; A=a;b ?
A =
1 2 3
4 5 6
>> B = A' % B is transpose of A
B =
1 4
2 5
3 6
Other ways to create B ? (hint: with a and b )
34
DR.AZIZUL HASAN
35. Matrix Operations( continued)
>> C = A*B % * is overloaded as matrix multiply operator
C =
14 32
32 77
>> D = A.*A % a .* turns matrix multiply to elemental multiply
D =
1 4 9
16 25 36
>> E = A./A % elemental divide
E =
1 1 1
1 1 1
>> who % list existing variables in workspace
Your variables are:
A B C D E a b d
35
DR.AZIZUL HASAN
36. Data Precisions
>> whos % detail listing of workspace variables
Name Size Bytes Class Attributes
A 2x3 48 double
B 3x2 48 double
C 2x2 32 double
D 2x3 48 double
E 2x3 48 double
a 1x3 24 double
b 1x3 24 double
c 1x3 24 double
>> A = single(A); % recast A to single data type to save memory
>> whos
Name Size Bytes Class
A 2x3 24 single
>> clear % delete all workspace variables
36
DR.AZIZUL HASAN
37. File Types
There are many types of files in MATLAB.
Only script-, function-, and mat-files are covered here:
1. script m-files (.m) -- group of commands; reside in base workspace
2. function m-files (.m) -- memory access controlled; parameters passed as
input, output arguments; reside in own workspace
3. mat files (.mat) -- binary (or text) files handled with save and load
4. mex files (.mex) -- runs C/FORTRAN codes from m-file
5. eng files (.eng) -- runs m-file from C/FORTRAN code
6. C codes (.c) – C codes generated by MATLAB compiler
7. P codes (.p) – converted m-files to hide source for security
• The Load Function
The load function reads binary files containing matrices generated by earlier
MATLAB sessions, or reads text files containing numeric data
37
DR.AZIZUL HASAN
38. Script m-file
Scripts are m-files containing MATLAB statements.If you have a group of
commands that are expected to be executed repeatedly, it is convenient
to save them in a file . . .
>> edit mytrig.m % enter commands in editor window
a=sin(x); % compute sine x (radians)
b=cos(x); % compute cosine x (radians)
disp( [‘a = ‘ num2str(a) ] ) % prints a; here, [ . . . ] constitutes a string array
disp( [‘b = ‘ num2str(b) ] ) % prints b
Select File/Save to save it as mytrig.m
A script shares same memory space from which it was invoked.
Define x, then use it in mytrig.m (mytrig can “see” x):
>> x=30*pi/180; % converts 30 degrees to radians
>> mytrig % x is accessible to mytrig.m; share same workspace
a = 0.5000
b = 0.8660
Script works as if sequentially inserting the commands in mytrig.m at the >>
38
DR.AZIZUL HASAN
39. MATLAB Script Files
A MATLAB script file (Called an M-file) is a text
(plain ASCII) file that contains one or more
MATLAB commands and, optionally, comments.
The file is saved with the extension ".m".
When the filename (without the extension) is issued
as a command in MATLAB, the file is opened, read,
and the commands are executed as if input from the
keyboard. The result is similar to running a program
in C. The following slide is the contents of an M-
file. Note that there are no prompts (>>).
39
DR.AZIZUL HASAN
40. % This is a MATLAB script file.
% It has been saved as “g13.m".
load g13.dat; %Load data file
voltage = g13( : , 4); %Extract volts vector
time = .005*[1:length(voltage)]; %Create time vector
plot (time, voltage) %Plot volts vs time
xlabel ('Time in Seconds') % Label x axis
ylabel ('Voltage') % Label y axis
title ('Bike Strain Gage Voltage vs Time')
grid on %Put a grid on graph
40
DR.AZIZUL HASAN
41. The preceding file is executed by issuing a MATLAB command:
>> g13
This single command causes MATLAB to look in the current directory,
and if a file g13.m is found, open it and execute all of the commands.
The result, in this case, is a plot of the data from g13.dat.
If MATLAB cannot find the file in the current working directory, an error
message will appear
When the file is not in the current working directory, a cd or chdir
command may be issued to change the directory.
>> cd a: % Make a: the current working directory
>> g13
41
DR.AZIZUL HASAN
42. Function m-files
• Declared with the key word function, with optional output parameters on the left and
optional input on the right of =. All other parameters within function reside in
function‟s own workspace; deleted upon exiting the function.
Use MATLAB editor to create file: >> edit average.m
function avg=average(x)
% function avg=average(x)
% Computes the average of x
% x (input) matrix for which an average is sought
% avg (output) the average of x
nx = numel(x); % number of elements in x; in own workspace
avg = sum(x)/nx; % avg is the average value on exit
end
• Recommendation: saves file with name same as function name
• It may be called from a script or another function
• >> a = average(1:3) % a = (1 + 2 + 3) / 3
a =
2
>> help average % prints contiguous lines with % at top of average
42
DR.AZIZUL HASAN
43. MATLAB Function Files
A MATLAB function file (called an M-file) is a text (plain ASCII) file that
contains a MATLAB function and, optionally, comments.
The file is saved with the function name and the usual MATLAB script file
extension, ".m".
A MATLAB function may be called from the command line or from any other
M-file
When the function is called in MATLAB, the file is accessed, the function is
executed, and control is returned to the MATLAB workspace.
Since the function is not part of the MATLAB workspace, its variables and
their values are not known after control is returned.
Any values to be returned must be specified in the function syntax
43
DR.AZIZUL HASAN
44. MATLAB Function Files
The syntax for a MATLAB function definition is:
function [val1, … , valn] = myfunc (arg1, … , argk)
where val1 through valn are the specified returned values
from the function and arg1 through argk are the values sent to
the function.
Since variables are local in MATLAB (as they are in C), the
function has its own memory locations for all of the variables
and only the values (not their addresses) are passed between
the MATLAB workspace and the function.
It is OK to use the same variable names in the returned value
list as in the argument. The effect is to assign new values to
those variables. As an example, the following slide shows a
function that swaps two values.
44
DR.AZIZUL HASAN
45. Example of a MATLAB Function File
function [ a , b ] = swap ( a , b )
% The function swap receives two values, swaps them,
% and returns the result. The syntax for the call is
% [a, b] = swap (a, b) where the a and b in the ( ) are the
% values sent to the function and the a and b in the [ ] are
% returned values which are assigned to corresponding
% variables in your program.
temp=a;
a=b;
b=temp;
To use the function a MATLAB program could assign values to two variables (the
names do not have to be a and b) and then call the function to swap them. For instance
the MATLAB commands:
>> x = 5 ; y = 6 ; [ x , y ] = swap ( x , y )
result in:
x =
6
y =
5
45
DR.AZIZUL HASAN
46. Referring to the function, the comments immediately following the function definition
statement are the "help" for the function. The MATLAB command:
>>help swap %displays:
The function swap receives two values, swaps them,and returns the result. The syntax
for the call is
[a, b] = swap (a, b) where the a and b in the ( ) are the values sent to the function and
the a and b in the [ ] are returned values which are assigned to corresponding
variables in your program.
The MATLAB function must be in the current working directory. If it is not, the
directory must be changed before calling the function.
If MATLAB cannot find the function or its syntax does not match the function call, an
error message will appear. Failure to change directories often results in the error
message:
Undefined function or improper matrix assignment
46
DR.AZIZUL HASAN
47. When the function file is not in the current working directory, a cd or chdir command
may be issued to change the directory.
>> cd a: % Make a: the current working directory
Unlike C, a MATLAB variable does not have to be declared before being used, and its
data type can be changed by assigning a new value to it.
For example, the function factorial ( ) on the next slide returns an integer when a
positive value is sent to it as an argument, but returns a character string if the argument
is negative.
function [n] = factorial (k)
% The function [n] = factorial(k) calculates and
% returns the value of k factorial. If k is negative,
% an error message is returned.
if (k < 0) n = 'Error, negative argument';
elseif k<2 n=1;
else
n = 1;
for j = [2:k] n = n * j; end
end
47
DR.AZIZUL HASAN
48. Some Frequently Used Functions
>> magic(n) % creates a special n x n matrix; handy for testing
>> zeros(n,m) % creates n x m matrix of zeroes (0)
>> ones(n,m) % creates n x m matrix of ones (1)
>> rand(n,m) % creates n x m matrix of random numbers
>> repmat(a,n,m) % replicates a by n rows and m columns
>> diag(M) % extracts the diagonals of a matrix M
>> help elmat % list all elementary matrix operations ( or elfun)
>> abs(x); % absolute value of x
>> exp(x); % e to the x-th power
>> fix(x); % rounds x to integer towards 0
>> log10(x); % common logarithm of x to the base 10
>> rem(x,y); % remainder of x/y
>> mod(x, y); % modulus after division – unsigned rem
>> sqrt(x); % square root of x
>> sin(x); % sine of x; x in radians
>> acoth(x) % inversion hyperbolic cotangent of x
48
DR.AZIZUL HASAN
49. MATLAB Display formats
• MATLAB supports 8 formats for outputting numerical
results.
format long 16 digits
format short e 5 digits plus exponent
format long e 16 digits plus exponent
format hex hexadecimal
format bank two decimal digits
format + positive, negative or zero
format rat rational number (215/6)
format short default display
49
DR.AZIZUL HASAN
50. MATLAB Graphics
Line plot
Bar graph
Surface plot
Contour plot
MATLAB tutorial on 2D, 3D visualization
tools as well as other graphics packages
available in our tutorial series.
50
DR.AZIZUL HASAN
51. PLOT OF GIVEN DATA
x
y
1 2 3 5 7 7.5 8
6.5 7 7 5.5 4 6 8
10
2
>> x=[1 2 3 5 7 7.5 8 10];
>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)
plot(x,y,‟line specifiers‟)
plot(x,y) A solid blue line connects the points with no markers.
plot(x,y,‟r‟) A solid red line connects the points with no markers.
plot(x,y,‟--y‟) A yellow dashed line connects the points.
plot(x,y,‟*‟) The points are marked with * (no line between the points.)
plot(x,y,‟g:d‟) A green dotted line connects the points which are marked with
diamond markers
51
DR.AZIZUL HASAN
55. Line Plot
>> t = 0:pi/100:2*pi;
>> y = sin(t);
>> plot(t,y)
55
DR.AZIZUL HASAN
56. Line Plot for title
>> xlabel(‘t’);
>> ylabel(‘sin(t)’);
>> title(‘The plot of t vs sin(t)’);
56
DR.AZIZUL HASAN
57. Multiple Line Plot
>> y2 = sin(t-0.25);
>> y3 = sin(t+0.25);
>> plot(t,y,t,y2,t,y3) % make 2D line plot of 3 curves
>> legend('sin(t)','sin(t-0.25)','sin(t+0.25',1)
57
DR.AZIZUL HASAN
58. 2D Bar Graph
>> x = magic(3); % generate data for bar graph
>> bar(x) % create bar chart
>> grid % add grid for clarity
58
DR.AZIZUL HASAN
59. Subplots
• Use subplots to divide a plotting window into
several panes.
>> x=0:0.1:10;
>> f=figure;
>> f1=subplot(1,2,1);
>> plot(x,cos(x),'r');
>> grid on;
>> title('Cosine')
>> f2=subplot(1,2,2);
>> plot(x,sin(x),'d');
>> grid on;
>> title('Sine');
0 5 10
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Cosine
0 5 10
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
Sine
59
DR.AZIZUL HASAN
60. Use MATLAB Command or
Function ?
• Many MATLAB utilities are available in both command and function forms.
• For this example, both forms produce the same effect:
• >> print –djpeg 'mybar' % print as a command
• >> print('-djpeg', 'mybar') % print as a function
• For this example, the command form yields an unintentional outcome:
• >> myfile = 'mybar'; % myfile is defined as a string
• >> print –djpeg myfile % as a command, myfile is treated as text
• >> print('-djpeg', myfile) % as a function, myfile is treated as a variable
• Other frequently used utilities that are available in both forms are:
• save, load
60
DR.AZIZUL HASAN
61. Example on mesh and surf – 3 dimensional plot
Supposed we want to visualize a function
Z = 10e(–0.4a) sin (2ft) for f = 2
when a and t are varied from 0.1 to 7 and 0.1 to 2, respectively
>>> [t,a] = meshgrid(0.1:.01:2, 0.1:0.5:7);
>>> f=2;
>>> Z = 10.*exp(-a.*0.4).*sin(2*pi.*t.*f);
>>> surf(Z);
>>> figure(2);
>>> mesh(Z);
Data visualization – plotting graphs
61
DR.AZIZUL HASAN
64. Surface Plot
>> Z = peaks; % generate data for plot; peaks returns function values
>> surf(Z) % surface plot of Z
Try these commands also:
>> shading flat
>> shading interp
>> shading faceted
>> grid off
>> axis off
>> colorbar
>> colormap(‘winter’)
>> colormap(‘jet’)
64
DR.AZIZUL HASAN
65. DR.AZIZUL HASAN 65
-2
-1
0
1
2
-1
-0.5
0
0.5
1
0
2
4
6
8
x
paraboloid
y
z
z= x.2
+4*y.2
Surface Plot
Plot the surface of the function f(x,y)=x^2+4y^2 for x [-2,2]and y[-1,1]
>> x=linspace(-2,2,50);
>> y=linspace(-1,1,50);
>>[x,y]=meshgrid(x,y);
>> z=x.^2+4*y.^2;
>> surf(x,y,z)
>> xlabel(‘x’);
>> ylable(‘y’);
>> zlable(‘z’);
66. DR.AZIZUL HASAN 66
Surface Plot
Plot the ellipsoid described by the equation x^2/4+y^2/16+z^2/9=1
>> [ x,y,z]=ellipsoid(0,0,0,2,4,3,50 );
>> surf(x,y,z)
>> xlabel(‘x’);
>> ylable(‘y’);
>> zlable(‘z’);
>>title(‘Surface plot by Dr Azizul Hasan’)
68. DR.AZIZUL HASAN 68
Surface Plot
Plot the Hyperboloid described by the equation x^2/4 -y^2/16+z^2=1
>> s=linspace(-1,1,25);
>> t=linspace(0,2*pi,50);
>>[s,t]=meshgrid(s,t);
>> x=2*cosh(s).*cos(t);
>> y=4*sinh(s);
>>z=cosh(s).*sin(t);
>>surf(x,y,z)
>> xlabel(‘x’);
>> ylable(‘y’);
>> zlable(‘z’);
>>title(‘Surface plot by Dr Azizul Hasan’)
69. DR.AZIZUL HASAN 69
Contour Plots
>> Z = peaks;
>> contour(Z, 20) % contour plot of Z with 20 contours
>> contourf(Z, 20); % with color fill
>> colormap('hot') % map option
>> colorbar % make color bar
70. DR.AZIZUL HASAN 70
Flow Control : For Loops
A for loop is used to repeat a statement or a group of statements for a fixed
number of times
for j=1:5 % use for-loops to execute iterations / repetitions
for i=1:3
a(i, j) = i + j ;
end
end
Utilities to initialize or define arrays: ones, rand, eye, . . .
Trigonometric and hyperbolic functions : sin, cos, sqrt, exp, . . .
These utilities can be used on scalar or vector inputs
>> a = sqrt(5); v = [1 2 3]; A = sqrt(v);
71. DR.AZIZUL HASAN 71
While loops
A while loop is used to execute a statement or a group of statements for an
indefinite number of times until the condition specified by while is no longer
satisfied.
For example : let us find all powers of 2 below 10000
w = 1; num = 1; i= 1;
while num < 10000
w = [ w; num];
i = i+1;
num= 2^i ;
end
w % display w
72. DR.AZIZUL HASAN 72
if Conditional
Scalar operation . . .
for j=1:3 % columns
for i=1:3 % rows
a(i,j) = rand; % generate a random number
if a(i,j) > 0.5
b(i,j) = 1;
end
end
end
Equivalent vector operations . . .
A = rand(3); % A is a 3x3 random number double array
B = zeros(3); % Initialize B as a 3x3 array of zeroes
B(A > 0.5) = 1; % set to 1 all elements of B for which A > 0.5
73. DR.AZIZUL HASAN 73
if –elseif-else statements
This construction provides a logical branching for computation. Here is an
example
For example :
i=6; j=21;
if i > 5
k = i;
else if (i>1) & (j= = 20)
k = 5*i +j;
else
k = 1;
end
Of course, you can have nested if statements as long as you have matching end
statements.
74. DR.AZIZUL HASAN 74
How to use For Loop and While Loop in MATLAB
Looping Statements: We can repeatedly execute a block of code using Loop
Control Statements
For Loop Statements: For loop is used to repeat the execution of group of
statements within the loop to a specified number of times. Each loop requires the
end keyword.
Example-1
Given: To Find the sum of first 5 Natural Numbers.
sum=0; %Initializing the sum variable
for i=1:5 %for loop – it iterates to the loop till i goes from 1 to 5
% after each iteration i is incremented by 1.
sum=sum + i; % Performing addition
disp(sum); % Displaying the output sum
end % End of for Loop
76. DR.AZIZUL HASAN 76
Explanation: We have initialized the variable sum
with value 0. for i = 1:5 statement means that it has
to execute the statements within the loop 5 times
and after each iteration the value of i is
incremented by 1. It is similar to writing as for i =
1:1:5 which tells that let loop get executed while i
value goes from 1 to 5 with an increment of 1 in i
value after each iteration. So, in the first iteration
the value of i = 1 so sum = 0 + 1 = 1. Similarly, in
the next iteration the value of i will be 2 so, sum = 1
+ 2 = 3. Hence it loop continues till the value of i
becomes 5 so, sum = 10 + 5 = 15.
77. DR.AZIZUL HASAN 77
for i = 1:1:5 which tells that let loop get executed while i value goes
from 1 to 5 with an increment of 1 in i value after each iteration. As can
be seen the output remains same. The default increment value is 1.Here
we can specify the increment value explicitly
78. DR.AZIZUL HASAN 78
Example-2 Nested For Loops
for i=1:2 %for each value of i the inner loop is executed
for j=2:3 %for 1 value of i the inner loop ie executed for all values of j
k=i+j;% Summation of i and j
str=sprintf(‘i: %d , j: %d , k: %d’,i,j,k);%printing on screen
str % Display
end % end of inner For Loop
end %end for outer For Loop
Explanation:
For each value of outer loop, the inner loop gets executed for every value of
the changing variable of the inner loop. In the above example we can see
that for i=1 first j would 2 and then in the next iteration of inner loop j would
become 3.Thus i=1, j=3. Now after every iteration of inner loop the outer
loop value gets increment i.e. i = 2, j = 1 and the process repeats.
79. DR.AZIZUL HASAN 79
NOTE: When nesting a number of while statements,
each while statement requires an end keyword. You can
programmatically exit a loop using a break statement, or skip to the
next iteration of a loop using a continue statement. It’ll be explained
to you later in this tutorial. We’ll perform the same example we used
for explaining For Loop but now using the while loop.
Output:
80. DR.AZIZUL HASAN 80
While Loop Statements: while statements loop as long as
a condition remains true. The execution of group of statements in the loop is
repeated till the expression is true.
Example-1:
Given: To Find the Sum of first 5 Natural Numbers.
sum = 0; %Initializing the sum variable
i=1; %Initializing the i variable with value 1.
while i<6 % While Loop: The statements inside the while loop are executed
%at every iteration as long as the condition remains true.
sum=sum+i; %Performing addition operation
i=i+1; %the i value is incremented by 1 at each iteration through the loop
disp(sum) %Display Statement
end %end of while loop
81. DR.AZIZUL HASAN 81
Explanation:
We have initialized the variable sum = 0 & the variable i = 1 which is used in
expression to repeat the execution of statements inside the while loop. At
First, since i=1 the expression i<6 is true. Hence the statements inside the
while loop would be executed i.e. sum = 0 + 1 = 1, i = 1 + 1 = 2. Now the value
of i =2 and the expression is again checked i<6, which is true. Hence again the
statements would be executed i.e. sum = sum + i = 1 + 2 = 3, i = i + 1 = 2 + 1 =
3. This process continues until the expression i<6 returns false.
82. DR.AZIZUL HASAN 82
How to control loop inside MATLAB
Loop Control Statements
Loop control statements change execution from its normal sequence.
break
The break statement terminates execution of for or while loop. Statements in the
loop that appear after the break statement are not executed. In nested loops,
break exits only from the loop in which it occurs. Control passes to the statement
following the end of that loop.
83. DR.AZIZUL HASAN 83
Syntax
break
Example:
Given: The initial value of a is 1.
Explanation:
The value of a is incremented after each iteration through loop. Now when
the value of a becomes 6. The expression of if block gets true and the
statement is displayed as can be seen from the output in the above image.
Break statement is executed and the while loop gets terminated which can
be seen as the statement after the break statement is not displayed and
also the value of a remains 6.
Continue
The continue statement is used for passing control to next iteration of for
or while loop. It forces the next iteration to take place without executing
the code in between.
Syntax:
continue
Example:
84. DR.AZIZUL HASAN 84
Given: The value of a is 1.
Explanation: When the value of a = 3 .The control goes into if block there the value
of a is incremented by 1 and the statement is displayed. Now continue statement is
encountered and we can see from the output in the above image that the
statements after the continue statement are not executed i.e. the value of a is also
not incremented and the statement is also not displayed. This the control is passed
to the next loop iteration and the between steps are not executed.
end
85. DR.AZIZUL HASAN 85
end
It is used to terminate a block of code, or indicate last array index
• end is used to terminate looping constructs like for & while & branching
constructs like if, switch.
• end also serves to delimit the scope.
• end also marks the termination of a function, although in many cases it is
optional. If your function contains one or more nested functions, then you must
terminate every function in the file, whether nested or not, with end.
Syntax:
End
return
It forces MATLAB to return control to the invoking function before it reaches the end
of the function. The invoking function is the function that calls the script or function
containing the call to return.
Syntax:
return
Example: function sq = square(x)
sq=x*x;
return
disp('After return statement');
sq=x*x*x;
end
86. DR.AZIZUL HASAN 86
Given: We have made a script file name square.m having code as per above image.
Explanation: As from Image in command window we call the function square and
passing the value 5 to the function. Now we get the output 25. i.e. the statement sq =
x*x is executed and returned. But the statements after the return are not executed. As
return passes the control to the invoking function. Hence once the return statement is
encountered the steps after it will not be executed
87. DR.AZIZUL HASAN 87
Cell Arrays
A cell array is a special array of arrays. Each element of the cell array may
point to a scalar, an array, or another cell array.
>> C = cell(2, 3); % create 2x3 empty cell array
>> M = magic(2);
>> a = 1:3; b = [4;5;6]; s = 'This is a string.';
>> C{1,1} = M; C{1,2} = a; C{2,1} = b; C{2,2} = s; C{1,3} = {1};
C =
[2x2 double] [1x3 double] {1x1 cell}
*2x1 double+ ‘This is a string.‘ *+
>> C{1,1} % prints contents of a specific cell element
ans =
1 3
4 2
>> C(1,:) % prints first row of cell array C; not its content
Related utilities: iscell, cell2mat
88. DR.AZIZUL HASAN 88
Structures
Ideal layout for grouping arrays that are related.
>> name(1).last = ‘Smith’; name(2).last = ‘Hess’;
>> name(1).first = ‘Mary’; name(2).first = ‘Robert’;
>> name(1).sex = ‘female’; name(2).sex = ‘male’;
>> name(1).age = 45; name(2).age = 50;
>> name(2)
ans =
last: 'Hess'
first: 'Robert'
sex: 'male'
age: 50
Alternative style:
>> name = struct(‘last’,,Smith’,’Hess’-, ‘first’,,Mary’,’Robert’-,…
(‘sex’,,female’,’male’-, ‘age’,,45,50-);
Related utilities: isstruct, fieldnames, getfield, isfield
89. 89
MATLAB Symbolic Mathematics
Tutorial
Related materials:
Tutorial on numerical solution of equations using MATLAB
Relationships between mathematical, MATLAB and Excel
expressions
MATLAB tutorials on analysis and plotting of data
Symbolic Math Toolbox User's Guide
Powerpoint lecture for algebra and calculus
Powerpoint lecture on symbolic solutions and Taylor series
Introductory MATLAB tutorials: See MATLAB help,
MATLAB, getting started. Mathworks, the company creating
MATLAB, has useful tutorials and links to others.
MATLAB‟s symbolic engine permits the user to do some
things easily that are difficult or impossible to do numerically.
DR.AZIZUL HASAN
90. 90
The following topics are covered:
Differentiation
Indefinite integrals
Definite integrals
Conversion to numeric (“double”) variables for
subsequent numeric calculations
Substitution
Plotting of equations and functions
Solution of equations: graphical approximations,
single equations, multiple simultaneous equations,
non-linear equations.
Limits
Taylor series
Variable precision arithmetic
DR.AZIZUL HASAN
91. 91
First do the Get Started and Demos in MATLAB‟s Product Help for the
Symbolic Math Toolbox.
In the following instructions, material in bold is to be entered in the
MATLAB command line and executed. This can be done by copying and
pasting using Ctrl c to copy onto the Clipboard and Ctrl v to paste from the
Clipboard. (Use the small finger on the left hand to press Ctrl while pressing
c or v with the index finger of the left hand at the same time. Ctrl x cuts the
highlighted material and places it on the Clipboard.)
When starting something new, it is advisable to clear the memory using the
“clear” command and the command window using “clc.” Otherwise, work
you‟ve done before might interfere with the new thing you‟re working on.
So enter:
>> clear, clc
The first step is to tell MATLAB that the variables to be used are symbolic.
This is most easily done using the “syms” command. For example, in the
following we will use x, y, a, b and c as symbolic quantities. So enter:
DR.AZIZUL HASAN
92. 92
>> syms x y a b c f g
In the Workspace window (or use >> whos) note that these variables are symbolic,
rather than the usual double precision numeric variables.
Differentiation: The MATLAB symbolic toolbox is very useful for
checking calculus problems. For example, to find diff_f = df/dx where f =
e-axx3bsin(cx) and a, b and c are unspecified constants, we do the following:
>> f=exp(-a*x)*x^(3*b)*sin(c*x), diff_f = diff(f,x)
Notice that the result is quite complex. To ask MATLAB to try to simplify
it, type:
>> diff_f_simp = simple(diff_f)
MATLAB uses several algorithms for algebraic simplification, and chooses
as a final answer the shortest of the results. It is possible that no simpler
expression will be found.MATLAB can take higher order differentials. For
example, to find diff2_f = d2f/dx2 we do
>> diff2_f=diff(f,x,2)
using the already defined expression for f.
DR.AZIZUL HASAN
93. 93
Indefinite integrals: Thus, for example, to find the indefinite integral int_g = ,
where g = e-axsin(cx), we do:
>> clear, clc, syms a c x; g=exp(-a*x)*sin(c*x), int_g = int(g,x)
Check this by differentiating:
>> diff_int = diff(int_g,x)
This should give back g, but it doesn‟t look the same because MATLAB doesn‟t
always give things in the simplest format. In this case, we again use the simple
command
>> diff_int_simp = simple(diff_int)
Sometimes MATLAB is not able to integrate an expression symbolically. For
example, try to find (where, as before, f = e-axx3bsin(cx) and a, b and c are
unspecified constants).
>> clear, clc, syms a b c x; f = exp(-a*x)*x^(3*b)*sin(c*x), int(f,x)
When MATLAB cannot find a solution, it gives a warning message and repeats
the command. When this happens, you‟re out of luck.
DR.AZIZUL HASAN
94. DR.AZIZUL HASAN 94
Definite integrals: For the definite integral, int_def_g =
gdx enter
>> clear, clc, syms a c x; g = exp(-a*x)*sin(c*x), int_def_g = int(g,x,-pi,pi)
When MATLAB is unable to find an analytical (symbolic) integral, such as with
>> clear, clc, syms x, int(exp(sin(x)),0,10)
A numerical solution can nevertheless be found using the “quad” command, follow the steps
below for more complex functions.
1. Create the function to be integrated in the MATLAB editor and save it to your Current
Directory, which must also be in the path (File / Set Path). For example, for our
exp(sin(x)) function, enter the following script into the editor and save as func1.m.
function out = func1(x)
out = exp(sin(x));
end
2. Then use either one of the following formats:
>> quad('func1',0,10)
or
>> quad(@func1,0,1)
95. DR.AZIZUL HASAN 95
Conversion to a double precision numeric variable: Often MATLAB's symbolic engine
produces a symbolic answer, as in:
>> clear, clc, syms x; h=exp(-x)*sin(x), int_def_h=int(h,x,-pi,pi)
where is retained in symbolic form (pi). Irrational numbers may also result, e.g. 4/3
rather than 1.3333. For use in subsequent numerical calculations, you must convert
symbolic results into numeric “double” variables by the “double” command:
>> int_def_h_doub=double(int_def_h)
This can also be accomplished by pasting the symbolic results into a new command line,
e.g. in this example:
>> -sinh(pi)
Substitution: Sometimes it is desired to substitute one value or parameter for another in
an expression. This can be done using the “subs” command.
For example, imagine we want a=2 and c=4 in int_def_g. This is done by:
>> clear, clc, syms a c x; g = exp(-a*x)*sin(c*x), int_def_g = int(g,x,-pi,pi)
>> int_sub=subs(int_def_g,{a,c},{2,4})
You may get a different result if you assign the values to the variables before an
integration or differentiation is performed. Try it in the above example and see what
happens. In this case, with a definite integral, it‟s not serious because the only difference
is the form of the result. For an indefinite integral, substituting for the variable of
integration (e.g., x) prior to integration would give the wrong result altogether.
96. DR.AZIZUL HASAN 96
Graphing equations and functions: MATLAB‟s symbolic engine has commands for
plotting symbolic equations and functions, appropriately starting with “ez.” For two-
dimensional graphs, we use “ezplot.” As an example here we use the equation for a
circle of radius 2, x2+y2 = 4.
Step 1: Move everything to the left-hand side of the equation, i.e. x2 + y2 – 4 = 0
Step 2: Clear and define x and y as symbolic.
Step 3: Define a variable equal to the left-hand side of the equation, inside single
straight quotation marks.
Step 4: Use ezplot, as follows:
>> clear, clc, lhs = 'x^2+y^2 - 4'; ezplot(lhs,[-3,3,-2.5,2.5])
The [-3,3,-2,2] tells MATLAB that the x scale is to go from -3 to +3, and the y scale is
to go from -2.5 to +2.5. Note that we have assigned x2 + y2 - 4 to the character variable
“lhs” (see the Workspace window or type >> whos).
You can edit the figure in the Figure window. First save it as “circle.fig” using
File/Save As so you can retrieve it later from the Command window, without having to
recreate it. Here are some things you can do in the Figure window When using Word, to
get straight quotation marks click on the File tab, then Options/Proofing/Auto Format and click
off "Straight quotes" with “smart quotes”. Do the same with Auto Correct Options/ Auto Format
As You Type.
97. DR.AZIZUL HASAN 97
Click on the arrow icon and then double-click on any portion of the figure you‟d
like to edit. In this way you can change the color and thickness of the curve, add
points, change the axes, edit the title.
Edit / Copy Figure to place it on the Windows Clipboard. Then you can paste it
into a Word document, for example.
While in the Figure window, press the Alt and Print Screen keys at the same time, to
place the entire figure window on the clipboard. This can also be pasted into a Word
document. Experiment with other equations.
We can also plot functions defined in a MATLAB script m file, such as that for func1
we created above for the definite integral that had to be found numerically using
“quad.” For such a function, we must put the name of the function in single quotation
marks, as in the following:
>> clear, clc, ezplot('func1',0,10)
Three-dimensional plots can be created using the ezmesh and ezsurf commands. For
these commands an explicit form must be used, i.e. z = f(x,y). It is the f(x,y) that is
entered into the command. The code below illustrates some possibilities. The lines
with % are comments and are not executed by MATLAB. Open the excellent
MATLAB editor by >> edit, cut and paste the code below into your editor, save it on
your Current Directory as symplot3D.m, make certain the Current Directory is in
MATLAB‟s path (File/Set Path).
98. DR.AZIZUL HASAN 98
% symplot3D.m
% Some 3d plots, where z = the expressions shown
% In the figure window, click on Tools, Rotate 3D.
% Then put cursor on figure, hold down left mouse,
% move cursor to rotate figure. Notice that this
% gives you a better feeling for its 3D shape.
% Have some fun and create your own shapes.
clear, clc
syms x y
ex1='sqrt(4-x^2-y^2)';
figure(1); ezsurf(ex1,[-2,2,-2,2]);
ex2='x^2-y^2';
figure(2); ezsurf(ex2);
ex3='x^2+2';
figure(3); ezmesh(ex3);
ex4='x + y';
figure(4); ezmesh(ex4);
Execute this in the Command window by
>>symplot3D
Select each figure in turn, and in the Figure window Tools / Rotate 3D. Put the cursor
anywhere on the figure, hold down the left mouse button, and move the mouse to rotate
the figure.
99. DR.AZIZUL HASAN 99
Solution of equations: The symbolic toolbox in MATLAB is capable of solving
many types of equations, including non-linear ones and several simultaneous
equations. The steps in solving one or more equations using “solve” are:
Step 1: Define the variables in the equations as symbolic using the “syms” command.
Step 2: Define the equations (see the examples below).
Step 3: Solve the equations using the “solve” command.
Step 4: If there is more than one solution, decide which is physically reasonable and
select it.
Step 5: Check the solution by substituting it back into the original equation(s).
Example 1: Find the two solutions to the classic quadratic equation, ax2 + bx + c = 0.
There are three ways to do this
1: >> clear, clc, syms x a b c; eq = 'a*x^2+b*x+c = 0', [x]=solve(eq,x)
Note that single quotation marks must be placed around an equation that is assigned to
a variable, here eq. If you don't specify the right side of the equation, solve assumes
that the expression equals zero. So here we could have used:
2: >> clear, clc, syms x a b c; expn = a*x^2 + b*x + c, [x]=solve(expn, x)
Alternately, we can use the double-equal sign inside the solve command to define the
equation:
3: >> clear, clc, syms x a b c; [x]=solve(a*x^2 + b*x == -c, x)
As expected, we obtain two solutions. Suppose we want only the first. This is
extracted by
>> x1 = x(1)
100. DR.AZIZUL HASAN 100
. Example 2: Find the solution to e2x=3y:
>> clear, clc, syms x y; eq = 'exp(2*x) = 3*y', [x] = solve(eq, x)
(Is the log in this solution the natural log or the log base 10
We use a similar procedure to solve simultaneous equations. First, let us look at a set
of linear equations, and then non-linear equations.
Example 3: Find the solution to the following set of linear equations:
2x-3y+4z = 5
y+4z+x = 10
-2z+3x+4y = 0
>> clear, clc, syms x y z;
>> eq1 = '2*x-3*y+4*z = 5'
>> eq2 = 'y+4*z+x = 10'
>> eq3 = '-2*z+3*x+4*y = 0'
>> [x,y,z] = solve(eq1,eq2,eq3,x,y,z)
Notice that we did not have to enter x, y and z in any particular order in defining the
equation variables (unlike the numerical MATLAB method using matrices with or
inv). However, the variables in the output are in alphabetical order, regardless of how
they are written in the command. So take care to list the variables in the brackets in
alphabetical order. For example, if you use [z,x,y] rather than [x,y,z] in the above
example the result produced for z is actually x, that for x is actually y, and that for y is
actually z. Again, the results may be symbolic and require conversion to numeric
form for subsequent calculations:
>> x_d = double(x), y_d = double(y), z_d = double(z)
101. DR.AZIZUL HASAN 101
Example 4: We can also solve simultaneous non-linear equations, e.g. y = 2ex and y = 3-
x2:
>> clear, clc, syms x y; eq1='y=2*exp(x)', eq2='y=3-x^2', [x,y]=solve(eq1,eq2,x,y)
Note that this gives only one solution; there are two as we see below. Again, to convert x
and y from symbolic variables to numeric double variables, use the “double” command.
(Use “whos” or look in the Workspace window to follow this transformation.)
We can obtain an approximate solution by plotting these two equations and looking at
their intersections. We first move everything to the left hand side of the equations, since
ezplot plots expessions and not equations.
>> clear, clc, exp1 = 'y - 2*exp(x)'; exp2 = 'y-3+x^2';
>> ezplot(exp1), hold on; ezplot(exp2); hold off
The "hold on" command tells MATLAB to write the following plots on top of the first
one, rather than replacing it. Approximate values of the solutions (intersections) can be
obtained in the Figure window by clicking on Tools / Zoom In, clicking on a desired
intersection to enlarge that area of the graph, clicking on Tools / Data Cursor, and then
clicking on that intersection again to give the approximate values of x and y there.
Compare these results with those found above using the solve command.
102. DR.AZIZUL HASAN 102
Example 5: There are equations with an infinite number of solutions, for example sin(x)
= 1/2.
It is helpful to see some of these solutions by plotting y = sin(x)-1/2 and seeing
approximately where it has values of zero:
>> clear, clc, exp1='y - sin(x) + 1/2', exp0='0'
>> ezplot(exp1,[-6,6,-2,1]), hold on; ezplot(exp0); hold off
The "hold on" command tells MATLAB to write following plots on top of the first one,
rather than replacing it. Plotting 0 puts a horizontal line on the graph. Intersections of
the sine wave with this line represent solutions of the first equation. Approximate values
can be obtained in the Figure window by clicking on Tools / Zoom In, clicking on a
desired intersection to enlarge that area of the graph, clicking on Tools / Data Cursor, and
then clicking on that intersection again to give the approximate values of x and y there.
Try this on the first two intersections to the right of the origin (x > 0). Write down your
results to compare with those found below using solve commands.
The symbolic solve command finds only two solutions, those between 0 and and
then stops:
>> clear, clc, syms x; eq = 'sin(x)-1/2=0'; [x] = solve(eq,x); x_doub=double(x)
But suppose we want the solution that lies between x = 4 and x = 10. This can be done
numerically in two ways. One is to use the evalin function as follows, with the range
specified for where a solution is to be found.
>> clear, clc, evalin(symengine,'numeric::solve(sin(x) = 1/2, x = 4..10)')
103. DR.AZIZUL HASAN 103
Limits: The symbolic toolbox also contains a command for finding limits of
expressions, e.g.:
>> clear, clc, syms x a; value = limit(sin(a*x)/x,x,0)
There are cases where the limit depends on the direction from which it is approached.
Consider the plot of tan(x) versus x generated by:
>> clear, clc, ezplot('tan(x)')
Suppose we want the value of tan(x) at x = /2. We could use MATLAB's numeric
engine as follows:
>> tan(pi/2)
Does this give a correct result? Recall that tan(/2) can be either + or -, depending
on whether we approach from the left or the right. The numeric solution is a very large
number, which might by okay for some applications but not for others. We can use the
symbolic engine to find the two correct solutions, as follows:
>> clear, syms x, tanhalfpiright = limit(tan(x),x,pi/2,'right')
>> tanhalfpileft = limit(tan(x),x,pi/2,'left')
104. DR.AZIZUL HASAN 104
Taylor series: Taylor series are polynomial approximations for functions that are
valid near a particular point. Differentials of increasingly higher order are used to
generate this polynomial. The syntax is taylor(expression, order, variable, point)
Example: Expand ex about x = 3 to order 5:
>> clear, clc, syms x; Tay_expx = taylor(exp(x), x, 'ExpansionPoint', 3,
'Order', 5)
This is exactly correct only at x = 3. Compare this approximation at x = 2 with the
exact value:
>> approx=subs(Tay_expx,x,2), exact=exp(2), frac_err=abs(1-approx/exact)
The approximation improves as one adds more terms to the polynomial (order), or
moves closer to the point about which the expansion was made. This can be
illustrated by:
>> ezplot(Tay_expx), hold on, ezplot(exp(x)), hold off
105. DR.AZIZUL HASAN 105
Summations: MATLAB‟s symbolic engine is also capable of doing symbolic
summations, even those with infinitely many terms! The “symsum” command is used.
Let us consider
where f(k) is a function of an integer k. The syntax to calculate this using
MATLAB is syms k, symsum(f,k,m,n). If a factorial (!) is desired, since ! is also a
numeric command, we must tell MATLAB to use the symbolic form by including the
term involving the factorial in the sym command. For example, if you want (1+2*k)!
in your expression you must include it as sym('(1+2*k)!'). Infinite sums are
particularly interesting, e.g.:
the solution for which is found by:
>> clear, clc, syms k x; symsum((-1)^k*x^(2*k + 1)/sym('(2*k + 1)!'), k, 0, Inf)
106. DR.AZIZUL HASAN 106
Variable Precision Arithmetic (VPA): We can control the precision with which MATLAB
performs calculations involving irrational numbers. We illustrate this using the golden ratio:
Use "digits" to find the current (default) number of digits.
>> clear, clc, digits
The default accuracy of MATLAB's numeric engine is really only 16 significant figures.
The VPA syntax for calculating R from S is: R = vpa(S) & R = vpa('S'), depending on
whether you want the answer accurate to about 16 significant figures or to full precision in
symbolic form. Find the difference between the results of calculating the golden ratio by
these two methods.
>> phi1 = vpa((1+sqrt(5))/2), phi2 = vpa('(1+sqrt(5))/2'), difference = phi1 - phi2
Which is closer to the correct irrational value? When "difference" is evaluated, MATLAB
takes phi2 and expresses it to the current number of digits. The number of digits to which the
answer is rounded off can be controlled by the optional argument D, i.e. vpa(S,D) or
vpa('S',D). Compare the following:
>> clear, phi1 = vpa((1+sqrt(5))/2, 4), phi2 = vpa('(1+sqrt(5))/2'), difference = phi1 -
phi2
>> clear, phi1 = vpa((1+sqrt(5))/2), phi2 = vpa('(1+sqrt(5))/2',4), difference = phi1 -
phi2
>> clear, phi1 = vpa((1+sqrt(5))/2,100), phi2 = vpa('(1+sqrt(5))/2',100),
difference = phi1 - phi2
Thus, increasing D beyond 32 does not improve the precision using the numerical format, but
does add more significant figures using the symbolic format (with the quotation marks). So
if you want to know an irrational number to more significant figures, use symbolic methods.
107. Polynomial Algebra (Convolution Operator)
• Polynomial products and factoring:
8
20
26
21
8
)
4
4
5
)(
2
3
( 2
3
4
5
2
3
2
x
x
x
x
x
x
x
x
x
x
>> p1=[1,3,2];
>> p2=[1,5,4,4];
>> pc=conv(p1,p2)
pc =
1 8 21 26 20 8
>> deconv(pc,p2)
ans =
1 3 2
>> deconv(pc,p1)
ans =
1 5 4 4
107
DR.AZIZUL HASAN
109. Polynomial Roots
• Polynomial roots
• Draw the graph between the interval [-6,6]
>>c = [1 0 -3 1 0 -9];
>>roots(c)
ans=
1.9316
0.5898+1.1934i
0.5898 – 1.1934i
-1.5556+0.4574i
-1.5556 – 0.4574i
>>fplot (@(x) ,[-6,6])
0
9
3 2
3
5
x
x
x
9
3 2
3
5
x
x
x
-6 -4 -2 0 2 4 6
-8000
-6000
-4000
-2000
0
2000
4000
6000
8000
109
DR.AZIZUL HASAN
110. Root of nonlinear equation
• Solve the Nonlinear equation f(x)=0,
• Example , sinx = exp (x)-5 and draw the graph between the
interval [-3,3]
>>x = fzero (@(x) sin(x)- exp (x)+5, 1) where 1 is initial
guess
X =
1.7878
>>fplot (@(x) sin(x)- exp (x)+5 ,[-3,3])
-3 -2 -1 0 1 2 3
-15
-10
-5
0
5
110
DR.AZIZUL HASAN
111. Plot of unit circle/Parametric
curve
>> theta= linspace(0,2*pi,100);
>> x = cos(theta);
>> y = sin(theta);
Plot(x,y)
>>Axis(„equal‟);
>>xlabel(„x‟)
>>ylabel(„y‟)
>>title(„circle of unit radius‟)
>>print
Or,
Suppose we want to draw the circle in script
file write above and save as from the file menu.
A dialog box should appear. Type circle.m as
the name of document make sure that the file is
being saved in the folder. Click save to the save
file. Now go back to matlab command
>> help circle
>>circle
111
DR.AZIZUL HASAN
112. DR.AZIZUL HASAN 112
Lab -01:
Objective: The Objective of this lab is to introduce an airthematic operations
of the matrix in Matlab.
Learning Outcomes. After conducting this lab we will be to able to know how
to compute
(i) addition of two matrix
(ii) subtraction of two matrix
(iii) multiplication of two matrix
(4) transpose of any matrix
(5) Inverse of the any matrix A
(6) determinant of any matrix
(7) Rank of any matrix A
(8) Characteristics equation of matrix
(9) Eigen value and Eigen vector of matrix
Given Example:
A = [1 2 3; 5 1 4; 3 2 1]
A =
1 2 3
5 1 4
3 2 -1
B = [5 -3 2 ; -3 8 4; 4 9 -2]
B =
5 -3 2
-3 8 4
4 9 -2
113. 113
Matlab Program:
clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
A= [1- 2 1;0 -2- 8 ;-4 5 9]; % create a matrix A
B= [1- 2 1;0 -2- 8 ;-4 5 9]; % create a matrix B
(1) X = A+B % create a sum matrix A and B
output. check by the computer. See output in command window.
(2) Y = A-B % create difference of matrix A and B
output.
(3) Z= A*B % create Product of matrix A and B
Output.
(4) T= A‟ % create transpose of matrix A
Output.
(5) I== inv(A) % create inverse of matrix A
Output.
(6) D= det(A) % create determinant of matrix A
Output.
DR.AZIZUL HASAN
114. 114
Matlab Program:
(7) R = rank(A) % create rank of matrix A
Output. R=
(8) P = poly(A) %create the coefficients of characteristic equation
Output. P=
(9) >> B = [5 -3 2; -3 8 4; 4 2 -9];
>>eig(B) % create eigen value of matrix B
ans =
-10.2206
4.4246
9.7960
>>[eigvec , eigval] = eig(B) ,or [V D] = eig(B) value and Eigen vector of matrix
eigvec =
0.1725 0.8706 -0.5375
0.2382 0.3774 0.8429
-0.9558 0.3156 -0.0247
Conclusion: Thus we have arithmatic solution of any matrix.
DR.AZIZUL HASAN
115. 115
Lab -02:
Objective: The Objective of this lab is to introduce to Solve the system of
linear equations by left division method in Matlab.
Learning Outcomes. After conducting this lab we will be to know how to
compute the solution of a system of linear simultaneous equations using left
division method .
Given Example: x-2y+z = 0
0-2y-8z = 8
-4x+5y+9z =-9
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
A= [1- 2 1;0 -2- 8 ;-4 5 9]; % create a matrix A
b = [0;8;-9]; % create a column vector b
X = Ab or x = inv(A)*B , % solve for x and the is
used to solve linear system of equations
Output: X = check by the computer. See output in command window.
Conclusion: Thus we have solution of simultaneous equation is
x = 3.4442 , y = 3.1982, z = 1.1868
DR.AZIZUL HASAN
116. 116
Lab -03:
Objective: Solve the system of equations by gauss elimination methods in Matlab.
Learning Outcomes. After conducting this lab we will be able to know how to
compute the solution of a system of linear simultaneous equations.
Given Example: 5x-3y+2z=10
-3x+8y+4z=20
2x+4y-9z =9
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
A= [5 -3 2;-3 8 4;2 4 -9]; % create a matrix A
b = [10;20;9]; % create a column vector b
C = [ A b]; % create the augmented matrix
X = rref(C) % row reduce echelon form of the
matrix
Output: X =
1 0 0 3.4442
0 1 0 3.1982
0 0 1 1.1868
Conclusion: Thus we have solution of simultaneous equation is
x = 3.4442 , y = 3.1982, z = 1.1868
DR.AZIZUL HASAN
117. 117
Lab -04:
Objective: The Objective of this lab is to introduce to polynomials in Matlab.
Learning Outcomes. After conducting this lab we will be to know how to
(i) How to represents the polynomial in matlab
(ii) Plot the polynomial.
(iii) Compute the roots for a given polynomials equation.
(iv) Plot the roots of ploynomial
(v) Evaluate the polynomial at x = 4
(vi) Compute the polynomial derivative
(vii) Compute the polynomial integration
Given Example:let us consider the polynomial
Matlab Program:
clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
(i) p= [3 15 0 -10 0 4 0 ]; % enter the coefficient of the polynomial equation
Out put: p = 3 15 0 -10 0 4 0
(ii) plot(p) % create the graph of the polynomial. See graph in figure window
grid on % create the grid on graph
legend(„six degree polynomial „)
x
x
x
x
x
p 4
10
15
3
)
( 3
5
6
DR.AZIZUL HASAN
118. 118
(iii) x = roots (p) % compute the roots for a given polynomials
Output: See in output in command window. we will get six roots.
(iv) plot(x) % create the graph of the roots of polynomials
See figure in figure window
(v) Y = polyval (p,x); %create the polynomial value at x
y = polyval(p,4) % Evaluate the polynomial at x = 4
Output:
(vi) polyder(p) %compute the polynomial derivative.
output.
(vii) polyint(p) % Compute the polynomial integration
Conclusion:
DR.AZIZUL HASAN
119. 119
Lab -05:
Objective: The Objective of this lab is to introduce to find the roots of nonlinear
equation by Bisection method in Matlab in the interval [.5 ,.9]
Learning Outcomes. After conducting this lab we will be able to compute the root
(solution )of a nonlinear equation.
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
a = .5; b = .9; % creates the initial interval
fa = a – cos(a); fb = b-cos(b); % creates the function values at a and b
for i = 1:10 % creates the iterations
c = (a+b)/2 % create the mid points of the interval
fc = c – cos(c) % create the function values of the iterative roots
if fa*fc < 0
b = c; fb = fc;
else
a = c ; fa = fc;
end
end
Output: see output in command window. c and f(c)
Conclusion:
0
)
cos(
x
x
DR.AZIZUL HASAN
120. 120
Lab -06:
Objective: The Objective of this lab is to introduce to find the roots of
nonlinear equation by Newton method in Matlab where
x0 = 0
Learning Outcomes. After conducting this lab we will be able to compute
the root (solution )of a nonlinear equation.
Matlab Program:
clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x(1) = 0 % initial first approximate root
for i = 1:10 % creates the iterations for loops
fx = x(i) – cos(x(i)) % create a function
fdx = 1+ sin(x(i)); % create a derivative of function
x(i+1) = x(i) – (fx/fdx); create the formula for the root
end
Output: see output in command window. x and fx
Conclusion:
0
)
cos(
x
x
DR.AZIZUL HASAN
121. 121
Lab -07:
Objective: The Objective of this lab is to introduce to find the roots of nonlinear
equation by Secant method in Matlab where interval is
[0 ,1]
Learning Outcomes. After conducting this lab we will be able to compute the
root (solution )of a nonlinear equation.
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x(1) = 0.0 ; x(2)= 1.0; % initial approximate roots
for i = 1:10 % creates the iterations for loops
fx1 = x(i) – exp(-x(i)) ; % create a function
fx2 = x(i+1)- exp(-x(i+1)); % create a value of function
x(i+2) = x(i+1) +(x(i+1)-x(i))*fx2/ (fx1-fx2); create the formula
end
Output: see output in command window.
Conclusion: write conclusion
0
)
(
x
e
x
x
f
DR.AZIZUL HASAN
122. 122
Lab -08:
Objective: The Objective of this lab is to introduce to find the roots of nonlinear
equation by Fixed point iteration method in Matlab
where x0 =0.5
Learning Outcomes. After conducting this lab we will be able to compute the
root (solution )of a nonlinear equation.
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
g = @(x) 2*sin(x); % create the function g which satisfy the initial
approximate roots
x0 = 0.5; % creates the initial guess
x1 = g(x0) % create a function
while abs(x1-x0)> 0.001 % create the iterations while loops
x0 = x1 % create the root
x1 = g(x0);
end
r=x1
Output: see output in command window.
Conclusion: write conclusion
0
)
sin(
2
x
x
DR.AZIZUL HASAN
123. 123
Lab -09:
Objective: The Objective of this lab is to introduce to find the solution of system of
linear equations 5x+2y+z=12, x+4y+2z=15, x+2y+5z=20 by Jacobi
method in Matlab where x =0 ,y=0, z=0
Learning Outcomes. After conducting this lab we will be able to compute the
solution of system of linear equations.
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x = 0; y=0; z=0; % creates the initial guess
while 1 % create the iterations while loops
x1 = (12-2*y-z)/5; % create the root
y1 = (15-x-2*z) /4;
z1=(20-x-2*y)/5;
if (( x==x1)&&(y==y1)&&(z==z1))
break;
end;
x=x1
y = y1
z = z1
end
Output: See output in command window.
Conclusion: write conclusion
DR.AZIZUL HASAN
124. DR.AZIZUL HASAN 124
Lab -10(i)
Objective: The Objective of this lab is to introduce interpolation in one dimension by
Matlab for x = 0,1,2,3,4,5, y = 1,-0.6,-1.4,3.2,-0.7,-6.4
Learning Outcomes. After conducting this lab we will be able to compute
linear, cubic and spline Interpolation at any point
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x = [0,1,2,3,4,5 ]; % enter the xdata
y = [1,-0.6,-1.4,3.2,-0.7,-6.4 ]; % enter the ydata
yi=interp1(x,y,xi,‟method‟); % interploation with xi
yi = interp1(x,y,1.5,‟linear‟) %fit the linear
Output: see output in command window.
yi = -1
(ii) yi=interp1(x,y,xi,‟spline‟)
Output: yi=-1.7817
(iii) yi = interp1(x,y,1.5,‟cubic‟)
(iii) plot(x,y,‟o‟,1.5,yi) % create the graph
Title („cubic interpolation of y‟)
Conclusion: write conclusion
125. 125
Lab -10 (ii)
Objective: The Objective of this lab is to introduce interpolating polynomial in
Matlab
for f(x)= 1/x where x = 2,4,5,8, y = 0.5,0.25,0.2,0.125
Learning Outcomes. After conducting this lab we will be able to compute
(i) Interpolating polynomial of degree n=3
(ii) interpolating polynomial values at any intermediate point of x= 2.6
(iii) plot the polynomial
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x = [2 4 5 8]; % enter the xdata
y = [0.5 .25 .2 .125]; % enter the ydata
p = polyfit(x,y,n); %fit the polynomial of degree n
p = polyfit(x,y,3) %fit the polynomial of degree n
Output: see output in command window.
p =
(ii) polyval(p,2.6) % polynomial value at x= 2.6
Output:
(iii) plot(p) % create the graph
Conclusion: write conclusion
DR.AZIZUL HASAN
126. 126
Lab -11:
Objective: The Objective of this lab is to fit the linear (straight line ) and second
degree (parabola) curve by the method of least squares in Matlab
for line (i) where x = 1 ,2,3,4,5, y = 14,27,40,55,68
parabola (ii) where x = 0,1,2,3,4 , y = 1, 5, 10, 22, 38
Learning Outcomes. After conducting this lab we will be able to fit the straight line
and parabola.
(ii) plot the line and parabola
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x = [1 2 3 4 5 ]; % enter the xdata
y = [14 27 40 55 68]; % enter the ydata
a = polyfit(x,y,1) %fit the data to linear equation
plot(x,y) % graph of the curve
xlabel(„x‟), ylabel(„y‟), title(„curve fitting‟) % disply the axixes
legend(„ straight line‟)
grid on
Output: see output in command window.
p =
(iii) plot(p) % create the graph
Conclusion: write conclusion
DR.AZIZUL HASAN
127. 127
Lab -11 (ii):
Objective: The Objective of this lab is to fit the second degree (parabola) curve by
the method of least squares in Matlab
parabola (ii) where x = 0,1,2,3,4 , y = 1, 5, 10, 22, 38
Learning Outcomes. After conducting this lab we will be able to fit the straight line
and parabola.
(ii) plot the line and parabola
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x = [0 1 2 3 4 ]; % enter the xdata
y = [1 5 10 22 38]; % enter the ydata
a = polyfit(x,y,2) %fit the data to second degree equation
plot(x,y) % graph of the curve
xlabel(„x‟), ylabel(„y‟), title(„curve fitting‟) % display the axis's
legend(„ Parabola‟)
grid on
Output: see output in command window.
p =
Conclusion: write conclusion
DR.AZIZUL HASAN
128. 128
Lab -12:
Objective: The Objective of this lab is to introduce to evaluate the definite integral
by trapezoidal rule and quadrature rule in Matlab
where , lower limit a = 0 , upper limit b= 6, n= 6
number of subdivision of interval
Learning Outcomes. After conducting this lab we will be able to find the solution of
definite integral
Matlab Program: clc; % clear the commands in command window
clear all; % clear all the variables currently stored in memory
close all; % close all figure window that are open
x = 0:1:6; % create a line space between 0 and 6
f = 1./(1+x); % create the value of the function at different points
trapz(f) % calculate the area by trapezoidal rule
Output:
integral = quad(„ f „ , a , b); % use quadrature to calculate area
integral = quad(„1./(1+x) „ ,0 ,6)
Output: see output in command window.
p =
(iii) plot(f) % create the graph
Conclusion: write conclusion
)
1
/(
1
)
( x
x
f
DR.AZIZUL HASAN
129. DR.AZIZUL HASAN 129
Lab -13:
Objective: The Objective of this lab is to introduce to evaluate the differential
equation dy/dx = -6y, y(0)=1 in script file Matlab
Learning Outcomes. After conducting this lab we will be able to find the solution of
differential equation
Matlab Program: clc; % clear the commands in command window
h=0.1 ; % step‟s size
N=10 ; % number of steps
y(1)=1; % initial value of y
for n=1:N
y(n+1)=y(n)+h*(-6*y(n)) % euler formula
x(n+1)=n*h;
end
Output: see output in command window.
(ii) plot(x,y) % create the graph
>>hold on
>>x=0:0.01:1;
ye = exp(-6*x); % exact numerical solution
Plot(x,y, „r‟), grid on
Conclusion
130. DR.AZIZUL HASAN 130
Lab -13(ii): Function File using user define function
Objective: The Objective of this lab is to introduce to evaluate the differential
equation dy/dx = x/y, y(0)=1 in Matlab by euler method
Learning Outcomes. After conducting this lab we will be able to find the solution of
differential equation
Matlab Program: function [x ,y] = eulermethod(f,x0,y0,xn,n)
% euler approximation for ODE initial value problem
% calculation of h from x0,xn and n
h= (xn-x0)/n ;
% intialization of x and y as column vectors
x=[xo zeros(1,n)];y=[y0 zeros(1,n)];
% calculation of x and y
for i =1:n
x(i+1)=x(i)+h;
y(i+1)=y(i)+h*f(x(i),y(i)):
end
Note:Create user- defined function file in editor window as eulermethod.m by saving it.
After this go in command winodow and type handle function as
>> f=@(x,y) x./y;
[x,y]=eulermethod(f,0,1,0.1,10)
Output:
>>g= @(x) sqrt(x.^2+1);
xe=[0:0.01:0.3];
ye= g(xe);
Plot(xe,ye,‟g‟, x, y,‟r‟)
131. DR.AZIZUL HASAN 131
Lab -14: Function File using built in function
Objective: The Objective of this lab is to introduce to evaluate the
differential equation dy/dx = xy^2+y, y(0)=1 in Matlab by ODE23
and ODE45 on the interval [0,.5]
Learning Outcomes. After conducting this lab we will be able to
find the solution of differential equation
Matlab Program: f=inline(„x*y^2+y‟);
[x,y]=ode23(f,[0 .5],1)
Output: we will get two output x and y
plot(x,y) see figure in figure window
if partition are given like h=0.1, then write
>> xvalues=0:0.1:0.5
>>[x,y]=ode23(f, xvalues,1)
Output:
Plot(x,y) see figure in figure window
Note: Replace ode45 in place of ode23
132. Integration Example
• Integration of cosine from 0 to π/2.
• Use mid-point rule for simplicity.
h
h
i
a
dx
x
dx
x
m
i
m
i
ih
a
h
i
a
b
a
)
)
(
cos(
)
cos(
)
cos( 2
1
1
1
)
1
(
mid-point of increment
cos(x)
h
a = 0; b = pi/2; % range
m = 8; % # of increments
h = (b-a)/m; % increment
132
DR.AZIZUL HASAN
133. Integration Example — using
for-loop
% integration with for-loop
tic
m = 100;
a = 0; % lower limit of integration
b = pi/2; % upper limit of integration
h = (b – a)/m; % increment length
integral = 0; % initialize integral
for i=1:m
x = a+(i-0.5)*h; % mid-point of increment i
integral = integral + cos(x)*h;
end
toc
133
DR.AZIZUL HASAN
134. Integration Example — using
vector form
% integration with vector form
tic
m = 100;
a = 0; % lower limit of integration
b = pi/2; % upper limit of integration
h = (b – a)/m; % increment length
x = a+h/2:h:b-h/2; % mid-point of m increments
integral = sum(cos(x))*h;
toc
134
DR.AZIZUL HASAN
135. Hands On Exercise Solution
a = 0; b=pi/2; % lower and upper limits of integration
m = 8; % number of increments
h = (b-a)/m; % increment size
x= a+h/2:h:b-h/2; % m mid-points
bh = bar(x,cos(x),1,'c'); % make bar chart with bars full width (1) and cyan („c‟)
hold % all plots will be superposed on same figure
x = a:h/10:b; % use more points at which to evaluate cosine
f = cos(x); % compute cosine at x
ph = plot(x,f,'r'); % plots x vs f, in red
% Compute integral with different values of m to study convergence
for i=1:10
n(i) = 10+(i-1)*10;
h = (b-a)/n(i);
x = a+h/2:h:b-h/2;
integral(i) = sum(cos(x)*h);
end
figure % create a new figure
plot(n, integral)
135
DR.AZIZUL HASAN
136. %code to plot a heart shape in MATLAB
%Adapted form http://www.walkingrandomly.com/?p=2326
%set up mesh
n=100;
x=linspace(-3,3,n);
y=linspace(-3,3,n);
z=linspace(-3,3,n);
[X,Y,Z]=ndgrid(x,y,z);
%Compute function at every point in mesh
F=320 * ((-X.^2 .* Z.^3 -9.*Y.^2.*Z.^3/80) ...
+ (X.^2 + 9.* Y.^2/4 + Z.^2-1).^3);
%generate plot
isosurface(F,0)
view([-67.5 2]);
%Adjust the colormap
cm=colormap('jet');
%Zero out all the green and blue
cm(:,2:3)=0;
colormap(cm);
Plot of a heart shape
136
DR.AZIZUL HASAN
137. REFERENCES
DR.AZIZUL HASAN 137
[1]The Math Works Inc., MATLAB: 7.8., The Math Works Inc.,
2009a.
[2] Numerical Method and using Matlab, Third Edition, John H.
Mathews and Kartis D. Frik 1999.
[3] Applied Numerical Methods with MATLAB® for Engineers
and Scientists , Third Edition , Steven C. Chapra
[4]Numerical Method for Computing Science Engineering and
Mathematics, John H. Mathews, 1989.
[5] Moler, C. B., Numerical Computing with MATLAB, Siam,
2011.
[6] Gilat., A., MATLAB. An introduction with Applications. John
Wiley and Sons,2004.
References:
138. DR.AZIZUL HASAN 138
[7]Burden, R.L., and Faires,J.D., "Numerical Analysis", 8thedition,
Thompson Brooks-Cole, 2005
[8] Fausett , L. V., "Numerical Methods: Algorithms and
Applications", Prentice-Hall, 2003
[9] Numerical Methods and Analysis, Buchanan, J. L., and Turner,
P. R.,1992
[10] Numerical Analysis, Third Edition, 2002, David Kincaid and
Ward Cheney.
[11]Rudra Pratap, Getting Started with Matlab, A Quick
introduction for Scientist and Engineers, Oxford University
Press 2010.
[12] Coombes, K. R., Hunt, B. R., Lipsman, R. L., Osborn, J.E., Stuck
G.J., .Differential Equations with MATLAB. John Wiley and
Sons, 2000.
139. DR.AZIZUL HASAN 139
[13]Charles A and W.W Cooper (2008), Non-linear Power of
Adjacent Extreme Points Methods in Linear Programming,
Econometrica Vol. 25(1) pp132-153.
[14] Shampine, L.F., Reichelt, M.W., The MATLAB ode suite, SIAM
J. Sci. Comput.18, 1-22,1997.
[15] Autar, K.K and Egwu, E (2008),
http://www.numericalmethods.eng.usf.edu Retrieved on
20thFebruary, 2014.
[16] McDonough, J.M (2001),Lecture in Computationl Numerical
Analysis . Dept. of Mechanical Engineering, University of
Kentucky.
[17] Allen, M.B and Isaacson E.L (1998), Numerical Analysis for
Applied Science. John Wiley and sons. Pp 188-195.
140. DR.AZIZUL HASAN 140
[18]APPLIED NUMERICALMETHODS USING MATLAB, Won
Young Yang Chung-Ang University, Korea, Wenwu Cao
Pennsylvania State UniversityTae-Sang Chung Chung- Ang
University, Korea ,John Morris The University of Auckland, New
Zealand A JOHN WILEY & SONS, INC., PUBLICATION 2005.
[19] Applied Numerical Analysis, Sixth Edition, Gerald and
Patrick , 2002.
[20] An Introduction to Numerical Analysis, Kendall E.
Atkinson, 1989.
[21] Laurene V. Fausett, Applied Numerical Analysis Using
Matlab. Second Edition.2009.