CE206 MATLAB Fundamentals
CE206 MATLAB Fundamentals
Course Outline
Introduction to hi-level computational programming tools
- MATLAB, Mathematica etc.
Course Layout
Problem sets/Assignments
- Approximately one per week - Individual submission in printed form - Include codes and figures
Class grading
- Approximately one per week - Solving a given problem in a given amount of time - Print out the codes and figures and keep it in file
Final Project/Assignment
- Individual or group submission
Requirements
- Basic familiarity with programming (e.g. CE204) - Knowledge on linear algebra, differential equations d i l h d and numerical methods (CE 205)
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 b M th l d i l k by Mathworks, I k Inc. g y Originally intended for interactive numerical computations I t f ith itt i Interfaces with programs written in other languages(C++, Fortran) Widely used in academia, research institutions and industry worldwide
MATLAB basics
MATLAB can be thought of as a super-powerful graphing calculator with many more buttons (i.e. 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
MATLAB as a calculator
Basic arithmetic operators (+, , *, /) used in conjunction with brackets ( )
-5/(4.8+5.32)^2 ans = -0.0488 (3+4i)*(3-4i) ans = 25 cos(pi/2) ans = 6.1230e-017 exp(acos(0.3)) ans = 3 5470 3.5470
5 (4.8 + 5.32) 2
Built in Built-in functions sin() asin() i () i () cos() acos() tan() atan() log() log10() exp() sqrt() abs() round()
(3 + 4i )(3 4i )
cos( / 2) (
cos 1 ( 0.3)
All computations in MATLAB are done in double precision (15 significant figures)
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Variables
Variable names and their types do not have to be declared in MATLAB. If a statement i t t t t is terminated with a semicolon ( ; ) th results i t d ith i l ), the lt are suppressed letters, Variable names must start with a letter followed by letters digits, and underscores. p The name of variable is not accepted if it is reserved word.
Example
>> x=-13; y = 5*x z = x^2+y x= 13; 5 x, x 2+y y = -65 z = 104
Variables
Commands involving variables
who: lists the names of the defined 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: = 2.2204e-016, smallest value by which two numbers 2 2204e 016 can differ inf: , infinity NAN or nan: not-a-number
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( )
>> a = [1 2 3 4 5 ] a = 1 2 3 >> b = [2;4;6;8;10] b = 2 4 6 8 10 >> si e(a) size(a) ans = 1 >> length(a) ans = 5
>> 0.32:0.1:0.6 ans = 0.3200 0.4200 0.5200 >> -1.4:-0.3:-2 ans = -1.4000 -1.7000 -2.0000
Subplot example
subplot(221), plot(x,y) b l t(221) l t( ) xlabel('x'),ylabel('sin 3 pi x') subplot(222), plot(x,cos(3*pi*x)) xlabel('x'),ylabel('cos xlabel('x') ylabel('cos 3 pi x') subplot(223), plot(x,sin(6*pi*x)) xlabel('x'),ylabel('sin 6 pi x') subplot(224) plot(x,cos(6*pi*x)) subplot(224), plot(x cos(6*pi*x)) 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 active. is at the top left, then the numbering continues across the row
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Subplot example
x = 0:.1:2*pi; 0:.1:2 pi; y = sin(x); p y plot(x,y,'b') grid on; hold on; plot(x,exp(-x),'r:*');
10
10
10
10
10
10
10
10
10
10
10
10
40
10
30
10
20
10
10
10
10
-1
10
10
10
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:
>> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9
4*a
More on Matrices
zeros(n) zeros(m,n) a d( , ) rand(m,n) eye(m,n) ones(n) ones(m,n) size(A) length(A) Returns a n n matrix of zeros Returns a m n matrix of zeros Returns a m n matrix of random numbers Returns a m n Identity matrix Returns a n n matrix of ones Returns a m n matrix of ones For a m n matrix A, returns the row vector [m,n] containing the number of rows and columns in matrix d l i ti Returns the larger of the number of rows or columns in A
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
>> d = [ 3 4 2] D = di (d) [-3 2], 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
>> i = [1, 3, 5]; j = [2,3,4]; >> v = [10 11 12]; >> S = sparse (i,j,v) S = ( , ) (1,2) 10 Creating a 5-by-4 sparse matrix S having (3,3) 11 only 3 non-zero values: (5,4) 12 S(1,2) = 10, >> T = full(S) S(3,3) = 11 and T = S(5,4) = 12 0 10 0 0 0 0 0 0 0 0 11 0 0 0 0 0 The full command displays the sparse 0 0 0 12 i matrix
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Matrix operations
Transpose Addition and Subtraction Scalar Multiplication Matrix Multiplication Matrix Inverse Matrix powers Determinant B = A C = A+B C = A-B
B = A where is a scalar A, C = A * B B = inv(A), A must be a square matrix B = A * A , A must be a square matrix det(A), A must be a square matrix
-standard standard -element-wise
for loop
Used when we want to repeat a segment of the code several times
Example: Test the assertion that the p ratio of the two successive values in the Fibonacci series approach the golden ratio of (5-1)/2 f . i.e. fn/fn-1 = (5-1)/2 where n = 3,4,5 ..
>> F(1) = 0; F(2) = 1; >> for i = 3:20 F(i) = F(i-1) + F(i-2); end >> plot(1:19, F(1:19)./F(2:20),'o' ) >> h ld on, xlabel('n') hold l b l(' ') >> plot(1:19, F(1:19)./F(2:20),'-' ) >> legend('Ratio of terms f_{n-1}/f_n') >> plot([0 20], (sqrt(5) 1)/2*[1 1] ' ') 20] (sqrt(5)-1)/2*[1,1],'--')
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
Example: 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; end d >> [n, S] ans = 6 91
CE 206: Engg. Computation Sessional Dr. Tanvir Ahmed
Example: Given x= sin(linspace(0 10*pi 100)) how many sin(linspace(0,10 pi,100)), of the entries are positive?
-1
-0.8
-0.6
-0.4
-0.2
0.2
0.4
0.6
0.8
Example 2 find the sum: 12 + 22 + 32 + . +1002 sum_sq=0; for n=1:100 sum_sq = sum_sq + n^2; end
CE 206: Engg. Computation Sessional
Sum_sq=sum((1:100).^2)
Vectorization
Dr. Tanvir Ahmed
Vectorized code is more efficient for MATLAB Use indexing and matrix operations to avoid loops
Saddle
0.5
0.5
-0.5
-0.5
-3 -3 -2 -1 0 1 2 3
0.5
-0.5
-1 4 2 0 -2 -2 -4 -4 2 0 4
Scripting
Script files are ASCII (text) files containing MATLAB commands.
Function m-files
Example: Write a function m-file which calculates the area of a triangle having sides a, b and c using the formula: Area = s ( s a)( s b)( s c) Where s = (a+b+c)/2 The function name. Also the name of the m-file where the function definition will be stored. List of inputs Purpose of the function and how it can be used. Mainly y to aid the future users The code
List of output(s) p ( )
function [A] = area(a,b,c) % C Compute th area of a t i t the f triangle whose l h % sides have length a, b and c. % Inputs: % a,b,c: Lengths of sides % Output: % A: area of triangle g s = (a+b+c)/2; A = sqrt(s*(s-a)*(s-b)*(s-c)); %%%%%%%%% end of area %%%%%%%%%%%
CE 206: Engg. Computation Sessional
Function overloading
MATLAB functions are generally overloaded Can take a variable number of inputs Can return a variable number of outputs You can overload your own functions by having variable input p g 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 function plotSin(f1,f2) x linspace(0,2 pi,f1 16+1); x=linspace(0,2*pi,f1*16+1); figure if nargin == 1 plot(x,sin(f1*x)); plot(x sin(f1*x)); elseif nargin == 2 disp('Two inputs were given'); d end
Dr. Tanvir Ahmed