ce206 matlab fundamentals
TRANSCRIPT
-
7/31/2019 CE206 MATLAB Fundamentals
1/43
CE 206: Engineering
ompu a on ess ona
1.50 Credits, 3hrs/week
Dr. Tanvir Ahmed
Assistant Professor
-
7/31/2019 CE206 MATLAB Fundamentals
2/43
Course Outline
Introduction to hi-level computational programming tools- MATLAB, Mathematica etc.
Application to numerical analysis- as c ma r x compu a ons- Solving system of linear equations- Solving non-linear equations
- Solving differential Equations- Interpolation and curve-fitting- Numerical differentiation- Numerical integration
- Solving mechanics problems- Numerical solution of e uation of motion etc.
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
3/43
References and Resources
The MATLAB help file documentation- Provided with the MATLAB software- www.mathworks.com
Course materials in m website
- Lecture slides for CE206- An introduction to MATLAB David Griffith
- .
You will also need:- Your CE205 Course references/Lecture slides
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
4/43
-
7/31/2019 CE206 MATLAB Fundamentals
5/43
-
7/31/2019 CE206 MATLAB Fundamentals
6/43
MATLAB basics
MATLAB can be thought of as a super-powerful graphingcalculator with many more buttons (i.e. built-in functions)
You can build up your own set of functions suited for a particular
It is an interpreted programming language
-commands are executed line by line
It is ca able of ra hicall re resentincomputational results simultaneously.
- Not possible in C++, Fortran
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
7/43
MATLAB as a calculator
Basic arithmetic operators (+, , *, /) used in conjunction withbrackets ( )
-5/(4.8+5.32)^2
ans =
2)32.58.4(
5
+
Built-in-0.0488
(3+4i)*(3-4i) )43)(43( ii +
functions
ans =252/cos
s n as ncos() acos()
ans =
6.1230e-017
log() log10()
exp() sqrt() exp(acos(0.3))
ans =
)3.0(cos
e abs() round()
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
.
-
7/31/2019 CE206 MATLAB Fundamentals
8/43
Numbers and Formats
All computations in MATLAB are done in double precision (15
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
significant figures)
-
7/31/2019 CE206 MATLAB Fundamentals
9/43
Variables
Variable names and their types do not have to be declared inMATLAB.
a statement s term nate w t a sem co on ; , t e resu tsare suppressed
,digits, and underscores.
The name of variable is not accepted if it is reserved word.
Example=- = * = ^ ,
y =
-65104
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
10/43
Variables
Commands involving variables
whos: lists the names and sizes of defined variables
clear: clears all variables clear name: clears the variable name
clc: clears the command window
Avoid using
ans: default variable name for the result.
pi: = 3.1415926 eps: = . e- , sma es va ue y w c wo num ers
can differ
inf: , infinity
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
NAN or nan: not-a-number
-
7/31/2019 CE206 MATLAB Fundamentals
11/43
Vectors
- Entries within a row are separated by spaces or commas.-Rows are separated by semicolons.- Vector properties using size( ) and length( )
a =a =
1 2 3 4 5
s ze aans =
1 5
b =2
>> length(a)ans =
6
8
5
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
12/43
Other methods of vector creation
The colon operator: generally a : b : c produces a vector ofentries starting with the value a, incrementing by the value bun ge s o c
>> 3:7ans =
3 4 5 6 7
>> 0.32:0.1:0.6
ans =0.3200 0.4200 0.5200
>> -1.4:-0.3:-2ans =-1.4000 -1.7000 -2.0000
linspace (a,b,n)
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
, .
-
7/31/2019 CE206 MATLAB Fundamentals
13/43
Graphics: plotting functions
>> x = linspace (0,1,11);>> y = sin(3*pi*x);xy
3sin=
,10 xor
Increasing the number of elements in x
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
14/43
Multiplots, titles, labels, linestyles and colors
>> plot(x,y,'w-',x,cos(3*pi*x),'g--')>> legend('Sin curve','Cos curve')>> title 'Multi- lot '>> xlabel('x axis'), ylabel('y axis')>> grid
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
15/43
Subplot example
>> su p ot , p ot x,y>> xlabel('x'),ylabel('sin 3 pi x')
>> subplot(222), plot(x,cos(3*pi*x))x a e x ,y a e cos p x>> subplot(223), plot(x,sin(6*pi*x))>> xlabel('x'),ylabel('sin 6 pi x')
, ,
>> xlabel('x'),ylabel('cos 6 pi x')
subplot(m, n, p)
subplot splits the figure window into an mxn array of smallth . -is at the top left, then the numbering continues across therow
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
16/43
Subplot example
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
17/43
Formatted text on plots
p o e rs erms n e sequence xn g ven y xn =
[1 + 1/n]n and then graph the function (x) = x3 sin2(3x) on the interval-1 x 1
>> set(0,'Defaultaxesfontsize',16);^
Default font
changed. .>> subplot (211)>> plot(n,x,'.',[0 max(n)],exp(1)*[1 1],...-- , mar ers ze ,>> title('x_n = (1+1/n)^n','fontsize',12)>> xlabel('n'), ylabel('x_n')
changed
Subscri t>> legend('x_n','y = e^1 = 2.71828...',4)>> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
>> subplot (212)
superscript
LineWidth>> x = -2:.02:2; y = x.^3.*sin(3*pi*x).^2;>> plot(x,y,'linewidth',2)>> le end ' = x^3sin^2 3 i x' 4
changed
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
>> xlabel('x)
characters
-
7/31/2019 CE206 MATLAB Fundamentals
18/43
Formatted text on plots
p o e rs erms n e sequence xn g ven y xn =
[1 + 1/n]n and then graph the function (x) = x3 sin2(3x) on the interval-1 x 1
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-
7/31/2019 CE206 MATLAB Fundamentals
19/43
Adding additional plots
hold on and hold off
hold on tells MATLAB to keep the current data plotted and addthe results of an further lot commands to the ra h. Hold offreleases the hold on the figure
= *
y = sin(x);
plot(x,y,'b')
grid on;
hold on;
plot(x,exp(-x),'r:*');
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
h l i d il il
-
7/31/2019 CE206 MATLAB Fundamentals
20/43
Other plotting commands: semilogx, semilogy
1010
.semilogx(10.^x,x)
10
.semilogy(x, 10.^x)
108
8
9
106
5
6
7
102
104
2
3
4
0 1 2 3 4 5 6 7 8 9 110
0
100
102
104
106
108
1010
0
1
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
O h l i d l l
-
7/31/2019 CE206 MATLAB Fundamentals
21/43
Other plotting commands: loglog
x = logspace(-1,2);
50
og og x,exp x ,'-s'grid on
1040
1030
10
1020
-1 0 1 210
0
10
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
M t i
-
7/31/2019 CE206 MATLAB Fundamentals
22/43
Matrices
A 2-D array, or matrix, of data is entered row by row, with spaces(or commas) separating entries within the row and semicolonsseparating the rows:
>> A = [1 2 3; 4 5 6; 7 8 9]
=1 2 34 5 6
7 8 9
A(j,k) gives jth row, kth column, A([1,3], :) all of rows 1 and 3A(:, 1) first column
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
N i l A C t ti
-
7/31/2019 CE206 MATLAB Fundamentals
23/43
Numerical Array Concatenation
a=[1 2;3 4]a =
1 2
3 4
Use square
brackets [ ]
cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a]
cat_a =
3 4 6 83 6 4 8 4*a5 10 6 12
15 20 18 24
Use [ ] to combine existing arrays as matrix elements
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
M M t i
-
7/31/2019 CE206 MATLAB Fundamentals
24/43
More on Matrices
zeros(n) Returns a n n matrix of zeros
zeros(m,n) Returns a m n matrix of zeros
rand m n
eye(m,n) Returns a m n Identity matrix
ones(n) Returns a n
n matrix of onesones(m,n) Returns a m n matrix of ones
size(A)
For a m n matrix A, returns the row
vector [m,n] containing the number of rowsan co umns n ma r x
length(A)Returns the larger of the number of rows orcolumns in A
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Diagonal Matrix
-
7/31/2019 CE206 MATLAB Fundamentals
25/43
Diagonal Matrix
First define a vector containing the values of the diagonalentries (in order) then use the diag function to form the matrix
>> = - , D = ag
d =-3 4 2D =
-3 0 0
0 4 00 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 thematrix.
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Sparse Matrix
-
7/31/2019 CE206 MATLAB Fundamentals
26/43
Sparse Matrix
These are generally large matrices that have a very smallproportion of non-zero entries
>> i = [1, 3, 5]; j = [2,3,4];
>> v = [10 11 12];>> S = sparse (i,j,v)S =(1,2) 10 - -
(3,3) 11(5,4) 12
=
only 3 non-zero values:S(1,2) = 10,
T =
0 10 0 0
S(3,3) = 11 andS(5,4) = 12
0 0 11 00 0 0 0 The full command displays the sparse
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
matr x
Matrix operations
-
7/31/2019 CE206 MATLAB Fundamentals
27/43
Matrix operations
Transpose B = A
Subtraction
C = A+B C = A-B
ScalarMultiplication
= , w ere s a sca ar
Matrix= *
Multiplication
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-
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
-element-wise
Standard matrix product operation
-
7/31/2019 CE206 MATLAB Fundamentals
28/43
Standard matrix product operation
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Elementwise matrix operations
-
7/31/2019 CE206 MATLAB Fundamentals
29/43
Elementwise matrix operations
To do element-wise operations, use the dot .(.*, ./,^ . .
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
for loop
-
7/31/2019 CE206 MATLAB Fundamentals
30/43
for loop
Used when we want to repeat a segment of the code several times
Exam le: Test the assertion that theratio of the two successive values in theFibonacci series approach the golden
ratio o (5-1)/2. i.e. fn/fn-1 = (5-1)/2 where n = 3,4,5..
>> F(1) = 0; F(2) = 1;>> for i = 3:20F(i) = F(i-1) + F(i-2);end
>> plot(1:19, F(1:19)./F(2:20),'o' )>> o on, x a e 'n'>> plot(1:19, F(1:19)./F(2:20),'-' )>> legend('Ratio of terms f_{n-1}/f_n')
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
p o , sqr - , , --
while loop
-
7/31/2019 CE206 MATLAB Fundamentals
31/43
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 neededExample: What is the greatest value of n that can be used in the sum
and get a value less than 100?
>> S = 1; n = 1;>> while S+ (n+1)^2 < 100
n = n+1; S = S + n^2;en>> [n, S]ans =
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Logical and relational operators
-
7/31/2019 CE206 MATLAB Fundamentals
32/43
Logical and relational operators
== Equal
~= Not equal
> Greater than
-2.0000 3.1416 5.0000
-5.0000 -3.0000 -1.0000
< Less than
x xans =0 1 0
>= reater or equa
> x > 3 | x == -3ans =
& && And
Or
0 1 10 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 if/else/elseif
-
7/31/2019 CE206 MATLAB Fundamentals
33/43
Flow control usingif/else/elseif
Example: Given *
count=0;
for n=1:length(x) , , ,of the entries are positive?
count=count+1;
end
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
en
The find command for vectors
-
7/31/2019 CE206 MATLAB Fundamentals
34/43
The findcommand for vectors
returns a list of the positions (indices) of the elements of avector satisfying a given condition.
Example: Produce a plot for y = e-x2 sin(3x) and mark all the points that havea value of y greater than 0.2
-
0.8
1
.>> y = sin(3*pi*x).*exp(-x.^2);>> k = find(y > 0.2)
0.4
0.6
=
Columns 1 through 129 10 11 12 13 22 23
-0.2
0
0.224 25 26 27 36Columns 13 through 15
37 38 39
-0.8
-0.6
-0.4
>> lot x ':' hold on
-1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1-1
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
>> plot(x(k),y(k),'o)
Avoiding loops: efficient coding
-
7/31/2019 CE206 MATLAB Fundamentals
35/43
o d g oops: e c e t cod g
Example 1: Given x= sin(linspace(0,10*pi,100)), how many of the entries arepositive?
count=0;for n=1:length(x)
count=count+1;end
Count=length(find(x>0));
en
Example 2 find the sum: 12 + 22 + 32 + . +1002
sum_sq=0;sum_sq = sum_sq + n^2;
end
Sum_sq=sum((1:100).^2)
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Avoiding loops: efficient coding
-
7/31/2019 CE206 MATLAB Fundamentals
36/43
g p g
Built-in functions (e.g. find, sum) will make it faster to writeand execute
count=0;
for n=1:len th xif x(n)>0count=count+1;
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
-
7/31/2019 CE206 MATLAB Fundamentals
37/43
g p p g
- The commandmeshgridis used to construct the (x, y) gridpoints
at certain intervals- ,
-Use a surface plot feature (e.g.mesh,surf) to plot the surface
= 2 2-
[X,Y] = meshgrid(2:.2:4, 1:.2:3);
Saddle
Z = (X-3).^2-(Y-2).^2;mesh(X,Y,Z)title('Saddle'), 0.5
1
xlabel('x'),ylabel('y')
-0.5
0
42.5
3-1
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
2
2.5
3
.
1
1.5
xy
Advanced graphics: surf and shading
-
7/31/2019 CE206 MATLAB Fundamentals
38/43
g p gSaddle
, . , .
Z = (X-3).^2-(Y-2).^2;surf(X,Y,Z)
0.5
1
t t e 'Sa eshading faceted
-0.5
0
shading flat
colorma ( ra ) 2.53
3.5
4
1.5
2
2.5
3-1
xy
Saddle
1
Saddle
0
0.5
0
0.5
42.5
3-1
-0.5
42.5
3-1
-0.5
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
2
2.5
3
.
11.5
2
xy2
2.5
3
.
11.5
2
xy
Advanced graphics: contour plot
-
7/31/2019 CE206 MATLAB Fundamentals
39/43
g p pa es e same argumen s as sur ormes
Example: Plot the contour of the surface defined by z = (sinx) (cosy) for x and - 3
x=-pi:0.1:pi;y=-pi:0.1:pi;
1
2
, =mes gr x,y ;Z =sin(X).*cos(Y);contour(X,Y,Z,'LineWidth',2) -1
0
-3 -2 -1 0 1 2 3
-3
-2
1
0
0.5
4-1
-0.5
mesh(X,Y,Z); hold on;contour(X,Y,Z)
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed-4
-2
0
2
-4
-20
Specialized plotting functions
-
7/31/2019 CE206 MATLAB Fundamentals
40/43
p p g
polar-to make polar plotsolar 0 0 01 2* i cos 0 0 01 2* i *2
bar-to make bar graphs
, ,
quiver-to add velocity vectors to a plot
=, ,
quiver(X,Y,rand(10),rand(10));
stairs- lot iecewise constant functions
stairs(1:10,rand(1,10));
-
fill([0 1 0.5],[0 0 1],'r');
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Scripting
-
7/31/2019 CE206 MATLAB Fundamentals
41/43
p g
Script files are ASCII (text) files containing MATLAB commands.
Commonly known as m-files because they have a .m extensionCE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Function m-files
-
7/31/2019 CE206 MATLAB Fundamentals
42/43
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 out ut s
The function name. Also the name of the m-file
where the function definition will be stored.
function [A] = area(a,b,c)List of inputs
Compute t e area o a tr ang e w ose
% sides have length a, b and c.% Inputs:
Purpose of thefunction and how itcan be used. Mainl
% a,b,c: Lengths of sides% Output:
% A: area of trian le
to aid the futureusers
s = (a+b+c)/2;A = sqrt(s*(s-a)*(s-b)*(s-c)); The code
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Function overloading
-
7/31/2019 CE206 MATLAB Fundamentals
43/43
MATLAB functions are generally overloaded
Can take a variable number of inputs
You can overload your own functions by having variable input
and out ut ar uments
The following function plots a sine wave with frequency f1 on the range [0, 2],
function plotSin(f1,f2)= * *figure
if nargin == 1
built in
function ,elseif nargin == 2
disp('Two inputs were given');contains thenumber of
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
ennputs