CE 206: Engineering Computation Sessionaltanvirahmed.buet.ac.bd/CE 206/CE206_MATLAB...
Transcript of CE 206: Engineering Computation Sessionaltanvirahmed.buet.ac.bd/CE 206/CE206_MATLAB...
CE 206 Engineering Computation Sessional
150 Credits 3hrsweek
Dr Tanvir Ahmed
Associate Professor
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Outline
Introduction to hi-level computational programming tools- MATLAB Mathematica etc
Application to numerical analysis- Basic matrix computations- Solving system of linear equations- Solving non-linear equations- Solving differential Equations- Interpolation and curve-fitting- Numerical differentiation- Numerical integration
Application to engineering problems- Solving mechanics problems- Numerical solution of equation of motion etc
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Introduction to MATLAB
MATLAB (MATrix LABoratory) is a fully-functional programming language
Original code written by Cleve Moler of UNM in the 1970s later released as a commercial package by Mathworks Inc
Originally intended for interactive numerical computations
Interfaces with programs written in other languages(C++ Fortran)
Widely used in academia research institutionsand industry worldwide
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB basics
MATLAB can be thought of as a super-powerful graphing calculator with many more buttons (ie built-in functions)
You can build up your own set of functions suited for a particular operation
It is an interpreted programming language-commands are executed line by line
It is capable of graphically representingcomputational results simultaneously
- Not possible in C++ Fortran
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
References and Resources
The MATLAB help file documentation- Provided with the MATLAB software- wwwmathworkscom
Materials in my web space(httpteacherbuetacbdtanvirahmed)- Lecture slides for CE206- ldquoAn introduction to MATLABrdquo David Griffith- ldquoGetting Started with MATLABrdquo Mathworks Inc
You will also need- Your CE205 Course referencesLecture slides
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Layout
Class grading- Approximately one per week- Solving a problem in a given amount of time- Print out the codes and figures and keep it in file
Mid-term Assessment- Solving a problem in a given amount of time
Final ProjectAssignment- Individual or group submission
Final Quiz
Requirements- Basic familiarity with programming (eg CE204)- Knowledge on linear algebra differential equations
and numerical methods (CE 205)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Outline
Introduction to hi-level computational programming tools- MATLAB Mathematica etc
Application to numerical analysis- Basic matrix computations- Solving system of linear equations- Solving non-linear equations- Solving differential Equations- Interpolation and curve-fitting- Numerical differentiation- Numerical integration
Application to engineering problems- Solving mechanics problems- Numerical solution of equation of motion etc
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Introduction to MATLAB
MATLAB (MATrix LABoratory) is a fully-functional programming language
Original code written by Cleve Moler of UNM in the 1970s later released as a commercial package by Mathworks Inc
Originally intended for interactive numerical computations
Interfaces with programs written in other languages(C++ Fortran)
Widely used in academia research institutionsand industry worldwide
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB basics
MATLAB can be thought of as a super-powerful graphing calculator with many more buttons (ie built-in functions)
You can build up your own set of functions suited for a particular operation
It is an interpreted programming language-commands are executed line by line
It is capable of graphically representingcomputational results simultaneously
- Not possible in C++ Fortran
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
References and Resources
The MATLAB help file documentation- Provided with the MATLAB software- wwwmathworkscom
Materials in my web space(httpteacherbuetacbdtanvirahmed)- Lecture slides for CE206- ldquoAn introduction to MATLABrdquo David Griffith- ldquoGetting Started with MATLABrdquo Mathworks Inc
You will also need- Your CE205 Course referencesLecture slides
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Layout
Class grading- Approximately one per week- Solving a problem in a given amount of time- Print out the codes and figures and keep it in file
Mid-term Assessment- Solving a problem in a given amount of time
Final ProjectAssignment- Individual or group submission
Final Quiz
Requirements- Basic familiarity with programming (eg CE204)- Knowledge on linear algebra differential equations
and numerical methods (CE 205)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Introduction to MATLAB
MATLAB (MATrix LABoratory) is a fully-functional programming language
Original code written by Cleve Moler of UNM in the 1970s later released as a commercial package by Mathworks Inc
Originally intended for interactive numerical computations
Interfaces with programs written in other languages(C++ Fortran)
Widely used in academia research institutionsand industry worldwide
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB basics
MATLAB can be thought of as a super-powerful graphing calculator with many more buttons (ie built-in functions)
You can build up your own set of functions suited for a particular operation
It is an interpreted programming language-commands are executed line by line
It is capable of graphically representingcomputational results simultaneously
- Not possible in C++ Fortran
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
References and Resources
The MATLAB help file documentation- Provided with the MATLAB software- wwwmathworkscom
Materials in my web space(httpteacherbuetacbdtanvirahmed)- Lecture slides for CE206- ldquoAn introduction to MATLABrdquo David Griffith- ldquoGetting Started with MATLABrdquo Mathworks Inc
You will also need- Your CE205 Course referencesLecture slides
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Layout
Class grading- Approximately one per week- Solving a problem in a given amount of time- Print out the codes and figures and keep it in file
Mid-term Assessment- Solving a problem in a given amount of time
Final ProjectAssignment- Individual or group submission
Final Quiz
Requirements- Basic familiarity with programming (eg CE204)- Knowledge on linear algebra differential equations
and numerical methods (CE 205)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB basics
MATLAB can be thought of as a super-powerful graphing calculator with many more buttons (ie built-in functions)
You can build up your own set of functions suited for a particular operation
It is an interpreted programming language-commands are executed line by line
It is capable of graphically representingcomputational results simultaneously
- Not possible in C++ Fortran
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
References and Resources
The MATLAB help file documentation- Provided with the MATLAB software- wwwmathworkscom
Materials in my web space(httpteacherbuetacbdtanvirahmed)- Lecture slides for CE206- ldquoAn introduction to MATLABrdquo David Griffith- ldquoGetting Started with MATLABrdquo Mathworks Inc
You will also need- Your CE205 Course referencesLecture slides
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Layout
Class grading- Approximately one per week- Solving a problem in a given amount of time- Print out the codes and figures and keep it in file
Mid-term Assessment- Solving a problem in a given amount of time
Final ProjectAssignment- Individual or group submission
Final Quiz
Requirements- Basic familiarity with programming (eg CE204)- Knowledge on linear algebra differential equations
and numerical methods (CE 205)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
References and Resources
The MATLAB help file documentation- Provided with the MATLAB software- wwwmathworkscom
Materials in my web space(httpteacherbuetacbdtanvirahmed)- Lecture slides for CE206- ldquoAn introduction to MATLABrdquo David Griffith- ldquoGetting Started with MATLABrdquo Mathworks Inc
You will also need- Your CE205 Course referencesLecture slides
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Layout
Class grading- Approximately one per week- Solving a problem in a given amount of time- Print out the codes and figures and keep it in file
Mid-term Assessment- Solving a problem in a given amount of time
Final ProjectAssignment- Individual or group submission
Final Quiz
Requirements- Basic familiarity with programming (eg CE204)- Knowledge on linear algebra differential equations
and numerical methods (CE 205)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Course Layout
Class grading- Approximately one per week- Solving a problem in a given amount of time- Print out the codes and figures and keep it in file
Mid-term Assessment- Solving a problem in a given amount of time
Final ProjectAssignment- Individual or group submission
Final Quiz
Requirements- Basic familiarity with programming (eg CE204)- Knowledge on linear algebra differential equations
and numerical methods (CE 205)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
MATLAB as a calculator
raquo -5(48+532)^2
ans =
-00488
raquo (3+4i)(3-4i)
ans =
25
raquo cos(pi2)
ans =
61230e-017
raquo exp(acos(03))
ans =
35470
2)32584(
5
)43)(43( ii
)2cos(
)30(cos 1
e
Basic arithmetic operators (+ ndash ) used in conjunction with brackets ( )
Built-in functions
sin() asin()
cos() acos()
tan() atan()
log() log10()
exp() sqrt()
abs() round()
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numbers and Formats
All computations in MATLAB are done in double precision (15 significant figures)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
bull Variable names and their types do not have to be declared inMATLAB
bull If a statement is terminated with a semicolon ( ) the resultsare suppressed
bull Variable names must start with a letter followed by lettersdigits and underscores
bull The name of variable is not accepted if it is reserved word
Examplegtgt x=-13 y = 5x z = x^2+y
y =
-65
z =
104
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Variables
Avoid using
ndash ans default variable name for the result
ndash pi π = 31415926 helliphellip
ndash eps ε= 22204e-016 smallest value by which two numbers can differ
ndash inf infin infinity
ndash NAN or nan not-a-number
Commands involving variables
ndash who lists the names of the defined variables
ndash whos lists the names and sizes of defined variables
ndash clear clears all variables
ndash clear name clears the variable name
ndash clc clears the command window
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Vectors
- Entries within a row are separated by spaces or commas-Rows are separated by semicolons- Vector properties using size( ) and length( )
gtgt a = [1 2 3 4 5 ]
a =
1 2 3 4 5
gtgt b = [246810]
b =
2
4
6
8
10
gtgt size(a)
ans =
1 5
gtgt length(a)
ans =
5
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other methods of vector creation
The colon operator generally a b c produces a vector of entries starting with the value a incrementing by the value buntil it gets to c
gtgt 37
ans =
3 4 5 6 7
gtgt 0320106
ans =
03200 04200 05200
gtgt -14-03-2
ans =
-14000 -17000 -20000
linspace (abn)
generates n equispaced points between a and b inclusive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Graphics plotting functions
gtgt x = linspace (0111)
gtgt y = sin(3pix)
gtgt plot(xy)
xy 3sin
10 xfor
Increasing the number of elements in x
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Multiplots titles labels linestyles and colors
gtgt plot(xylsquob-xcos(3pix)g--)
gtgt legend(Sin curveCos curve)
gtgt title(Multi-plot )
gtgt xlabel(x axis) ylabel(y axis)
gtgt grid
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
gtgt subplot(221) plot(xy)
gtgt xlabel(x)ylabel(sin 3 pi x)
gtgt subplot(222) plot(xcos(3pix))
gtgt xlabel(x)ylabel(cos 3 pi x)
gtgt subplot(223) plot(xsin(6pix))
gtgt xlabel(x)ylabel(sin 6 pi x)
gtgt subplot(224) plot(xcos(6pix))
gtgt xlabel(x)ylabel(cos 6 pi x)
subplot(m n p)
subplot splits the figure window into an mxn array of small axes and makes the pth one active Note - the first subplot is at the top left then the numbering continues across the row
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Subplot example
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
gtgt set(0Defaultaxesfontsize16)
gtgt n = 1100 x = (1+1n)^n
gtgt subplot (211)
gtgt plot(nx[0 max(n)]exp(1)[1 1]
--markersize8)
gtgt title(x_n = (1+1n)^nfontsize12)
gtgt xlabel(n) ylabel(x_n)
gtgt legend(x_ny = e^1 = 2718284)
gtgt
gtgt subplot (212)
gtgt x = -2022 y = x^3sin(3pix)^2
gtgt plot(xylinewidth2)
gtgt legend(y = x^3sin^2 3pi x4)
gtgt xlabel(xlsquo)
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
Default font changed
Markersizechanged
Subscriptsuperscript
LineWidthchanged
Latin characters
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Formatted text on plots
plot the first 100 terms in the sequence xn given by xn =[1 + 1n]n and then graph the function Ф(x) = x3 sin2(3πx) on the interval -1 le x le 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and add the results of any further plot commands to the graph Hold off releases the hold on the figure
raquo x = 012pi
raquo y = sin(x)
raquo plot(xyb)
raquo grid on
raquo hold on
raquo plot(xexp(-x)r)
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
0 1 2 3 4 5 6 7 8 9 1010
0
102
104
106
108
1010
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands semilogx semilogy
x = 00110
semilogx(10^xx)
100
102
104
106
108
1010
0
1
2
3
4
5
6
7
8
9
10
x = 00110
semilogy(x 10^x)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Other plotting commands loglog
10-1
100
101
102
100
1010
1020
1030
1040
1050
x = logspace(-12)
loglog(xexp(x)-s)
grid on
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrices
A 2-D array or matrix of data is entered row by row with spaces (or commas) separating entries within the row and semicolons separating the rows
gtgt A = [1 2 3 4 5 6 7 8 9]
A =
1 2 3
4 5 6
7 8 9
Extracting bits of matrices
A(jk) gives jrsquoth row krsquoth columnA(2312) rows 2 through 3 and columns 1 through 2A([13] ) all of rows 1 and 3A( 1) first column
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Numerical Array Concatenation
raquo a=[1 23 4]
a =
1 2
3 4
raquo cat_a=[a 2a 3a 4a 5a 6a]
cat_a =
1 2 2 4
3 4 6 8
3 6 4 8
9 12 12 16
5 10 6 12
15 20 18 24
Use square
brackets [ ]
4a
Use [ ] to combine existing arrays as matrix ldquoelementsrdquo
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
More on Matrices
zeros(n) Returns a n ⅹ n matrix of zeros
zeros(mn) Returns a m ⅹ n matrix of zeros
rand(mn) Returns a m ⅹ n matrix of random numbers
eye(mn) Returns a m ⅹ n Identity matrix
ones(n) Returns a n ⅹ n matrix of ones
ones(mn) Returns a m ⅹ n matrix of ones
size(A)
For a m ⅹ n matrix A returns the row vector [mn] containing the number of rows and columns in matrix
length(A)Returns the larger of the number of rows or columns in A
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Diagonal Matrix
First define a vector containing the values of the diagonal entries (in order) then use the diag function to form the matrix
gtgt d = [-3 4 2] D = diag(d)
d =
-3 4 2
D =
-3 0 0
0 4 0
0 0 2
This command is useful when we need to construct very large matrices
If A is a matrix diag(A) extracts the diagonal elements of the matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Sparse Matrix
These are generally large matrices that have a very small proportion of non-zero entries
gtgt i = [1 3 5] j = [234]
gtgt v = [10 11 12]
gtgt S = sparse (ijv)
S =
(12) 10
(33) 11
(54) 12
gtgt T = full(S)
T =
0 10 0 0
0 0 0 0
0 0 11 0
0 0 0 0
0 0 0 12
Creating a 5-by-4 sparse matrix S having only 3 non-zero valuesS(12) = 10 S(33) = 11 and S(54) = 12
The ldquofullrdquo command displays the sparse matrix
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Matrix operations
Transpose B = Arsquo
Addition and Subtraction
C = A+B C = A-B
Scalar Multiplication
B = αA where α is a scalar
Matrix Multiplication
C = A B
Matrix Inverse B = inv(A) A must be a square matrix
Matrix powers B = A A A must be a square matrix
Determinant det(A) A must be a square matrix
Operators ^ and have two modes of operation-standard-element-wise
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Standard matrix product operation
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Elementwise matrix operations
To do element-wise operations use the dot ( ^) BOTH dimensions must match (unless one is scalar)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
for loop
Used when we want to repeat a segment of the code several times
gtgt F(1) = 0 F(2) = 1
gtgt for i = 320
F(i) = F(i-1) + F(i-2)
end
gtgt plot(119 F(119)F(220)o )
gtgt hold on xlabel(n)
gtgt plot(119 F(119)F(220)- )
gtgt legend(Ratio of terms f_n-1f_n)
gtgt plot([0 20] (sqrt(5)-1)2[11]--)
Example Test the assertion that the ratio of the two successive values in the Fibonacci series approach the golden ratio of (radic5-1)2 ie fnfn-1 = (radic5-1)2 where n = 345 hellip
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
while loop
when we want to repeat a segment of the code several times until some logical condition is satisfied
The while loop is used when we do not know for certain how many iterations may be needed
gtgt S = 1 n = 1
gtgt while S+ (n+1)^2 lt 100
n = n+1 S = S + n^2
end
gtgt [n S]
ans =
6 91
Example What is the greatest value of n that can be used in the sum
and get a value less than 100
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Logical and relational operators
== Equal
~= Not equal
gt Greater than
lt Less than
gt= Greater or equal
lt= Less or equal
amp ampamp And
| || Or
x =
-20000 31416 50000
-50000 -30000 -10000
gtgt x gt 3 amp x lt 4
ans =
0 1 0
0 0 0
gtgt x gt 3 | x == -3
ans =
0 1 1
0 1 0
Matlab represents true and false by means of the integers 0 and 1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Flow control using ifelseelseif
Example Given x= sin(linspace(010pi100)) how many of the entries are positive
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
-1 -08 -06 -04 -02 0 02 04 06 08 1-1
-08
-06
-04
-02
0
02
04
06
08
1
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
The find command for vectors
Example Produce a plot for y = e-x2 sin(3πx) and mark all the points that have a value of y greater than 02
gtgt x = -1051
gtgt y = sin(3pix)exp(-x^2)
gtgt k = find(y gt 02)
k =
Columns 1 through 12
9 10 11 12 13 22 23
24 25 26 27 36
Columns 13 through 15
37 38 39
gtgt plot(xy) hold on
gtgt plot(x(k)y(k)olsquo)
returns a list of the positions (indices) of the elements of a vector satisfying a given condition
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
Example 1 Given x= sin(linspace(010pi100)) how many of the entries are positive
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Count=length(find(xgt0))
Example 2 find the sum 12 + 22 + 32 + helliphelliphelliphelliphellip +1002
sum_sq=0
for n=1100
sum_sq = sum_sq + n^2
end
Sum_sq=sum((1100)^2)
Using the ldquofindrdquo command
Vectorization
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Avoiding loops efficient coding
Built-in functions (eg find sum) will make it faster to write and execute
count=0
for n=1length(x)
if x(n)gt0
count=count+1
end
end
Vectorized code is more efficient for MATLAB
Use indexing and matrix operations to avoid loops
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics plotting surfaces
- The command meshgrid is used to construct the (x y) gridpointsat certain intervals
- Evaluate the function z = f(xy) at all the gridpoints
-Use a surface plot feature (eg meshsurf) to plot the surface
Example Plot the surface defined by z = (x - 3)2 + (y ndash 2)2 for 2le x le 4 amd 1 le y le 3
[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
mesh(XYZ)
title(Saddle)
xlabel(x)ylabel(y)
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics surf and shading[XY] = meshgrid(224 123)
Z = (X-3)^2-(Y-2)^2
surf(XYZ)
title(Saddlelsquo)
shading faceted
shading flat
colormap(gray)2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y2
25
3
35
4
1
15
2
25
3-1
-05
0
05
1
x
Saddle
y
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Advanced graphics contour plot
x=-pi01pi
y=-pi01pi
[XY]=meshgrid(xy)
Z =sin(X)cos(Y)
contour(XYZLineWidth2)
Takes the same arguments as surf or mesh
Example Plot the contour of the surface defined by z = (sinx) (cosy) for ndashπ le x le πand - π le y le π
-3 -2 -1 0 1 2 3
-3
-2
-1
0
1
2
3
-4
-2
0
2
4
-4
-2
0
2
4-1
-05
0
05
1
mesh(XYZ) hold on
contour(XYZ)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Specialized plotting functions
polar-to make polar plots
polar(00012picos((00012pi)2))
bar-to make bar graphs
bar(110rand(110))
quiver-to add velocity vectors to a plot
[XY]=meshgrid(110110)
quiver(XYrand(10)rand(10))
stairs-plot piecewise constant functions
stairs(110rand(110))
fill-draws and fills a polygon with specified vertices
fill([0 1 05][0 0 1]r)
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
Script files are ASCII (text) files containing MATLAB commands
Commonly known as m-files because they have a m extension
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Scripting
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
List of output(s)
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function m-files
function [A] = area(abc)
Compute the area of a triangle whose
sides have length a b and c
Inputs
abc Lengths of sides
Output
A area of triangle
s = (a+b+c)2
A = sqrt(s(s-a)(s-b)(s-c))
end of area
Example Write a function m-file which calculates the area of a triangle having sides a b and c using the formula Area = Where s = (a+b+c)2))()(( csbsass
List of inputs
The function name Also the name of the m-file where the function definition will be stored
Purpose of the function and how it can be used Mainly to aid the futureusers
The code
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs
MATLAB functions are generally overloaded1048766 Can take a variable number of inputs1048766 Can return a variable number of outputs
You can overload your own functions by having variable input and output arguments
The following function plots a sine wave with frequency f1 on the range [0 2π] uses f1 as the input but displays a message when two inputs are given
CE 206 Engg Computation Sessional Dr Tanvir Ahmed
Function overloading
function plotSin(f1f2)
x=linspace(02pif116+1)
figure
if nargin == 1
plot(xsin(f1x))
elseif nargin == 2
disp(Two inputs were given)
end
built in function nargin
contains the number of inputs