Introduction To MATLAB: Sajid Gul Khawaja
Introduction To MATLAB: Sajid Gul Khawaja
Introduction
2
What is MATLAB ?
MATLAB is a computer program that combines computation and visualization power that makes it particularly useful tool for engineers.
MATLAB is an executive program, and a script can be made with a list of MATLAB commands like other programming language.
manage variables import and export data perform calculations generate plots develop and manage files for use with MATLAB.
MATrix LABoratory
3
www.mathworks.com Advantages of MATLAB Ease of use Platform independence Predefined functions Plotting
MATLAB Screen
4
Command Window type commands Current Directory View folders and mfiles Workspace View program variables Double click on a variable to see it in the Array Editor Command History view past commands save a whole session using diary
Variables
5
double precision
Variables Types
6
Variable types Numeric Logical Character and string Cell and Structure Function handle
Variables (cont)
7
Variable names:
May contain only letters, digits, and the underscore _ MATLAB is case sensitive, i.e. one & OnE are different variables. MATLAB only recognizes the first 31 characters in a variable name. Variable = number; Variable = expression;
>> tutorial = 1234; >> tutorial = 1234 tutorial = 1234
Assignment statement:
Example:
NOTE: when a semi-colon ; is placed at the end of each command, the result is not displayed.
Variables (cont)
8
min, max, sqrt, cos, sin, tan, mean, median, etc Funny things happen when you do this i, j, eps, nargin, end, pi, date, etc i, j are reserved as complex numbers initially
names for the variables. Never define a variable with the same name as a MATLAB function or command.
Special Variables
9
Special Values
MATLAB includes a number of predefined special values. These values can be used at any time without initializing them. These predefined values are stored in ordinary variables. They can be overwritten or modified by a user. If a new value is assigned to one of these variables, then that new value will replace the default one in all later calculations. >> circ1 = 2 * pi * 10; >> pi = 3; >> circ2 = 2 * pi * 10;
Never change the values of predefined variables.
Special variables:
ans : default variable name for the result pi: = 3.1415926 eps: = 2.2204e-016, smallest amount by which 2 numbers can differ. Inf or inf : , infinity NaN or nan: not-a-number
who: lists the names of defined variables whos: lists the names and sizes of defined variables clear: clears all varialbes, reset the default values of special variables. clear name: clears the variable name clc: clears the command window clf: clears the current figure and the graph window.
Interactive Commands
11
Format of output Defaults to 4 decimal places Can change using format statement format long changes output to 15 decimal places
Operators (arithmetic)
+ addition - subtraction * multiplication / division ^ power complex conjugate transpose
12
Operators
13
Operation
MATLAB form
ab ab a / b = a/b a \ b = b/a a+b b a^b a*b a/b a\b a+b a-b
and operators
== Equal to
~= Not equal to
< Strictly smaller > Strictly greater
| Or operator
.* ./ .^
Order of Operations
16
Parentheses
Exponentiation
Multiplication and division have equal precedence Addition and subtraction have equal precedence
Arrays
The fundamental unit of data in MATLAB
Row and column indices of an array start from 1. Arrays can be classified as vectors and
matrices.
Vector: Array with one dimension Matrix: Array with more than one dimension Size of an array is specified by the number of rows
and the number of columns, with the number of rows mentioned first (For example: n x m array).
Total number of elements in an array is the product of the number of rows and the number of columns.
Arrays
20
Variables and Arrays Array: A collection of data values organized into rows
and columns, and known by a single name.
Row 1 Row 2 Row 3 arr(3,2) Row 4 Col 1 Col 2 Col 3 Col 4 Col 5
21
1 2 a= 3 4 5 6 b=[1 2 3 4] 1 c= 3 5 a(2,1)=3
Row # Column #
3x2 matrix 6 elements 1x4 array 4 elements, row vector 3x1 array 3 elements, column vector
b(3)=3
c(2)=3
Vectors
22
A row vector in MATLAB can be created by an explicit list, starting with a left
bracket, entering the values separated by spaces (or commas) and closing the vector with a right bracket. A column vector can be created the same way, and the rows are separated by semicolons. Example: >> x = [ 0 0.25*pi 0.5*pi 0.75*pi pi ] OR x = [ 0 0.25*pi, 0.5*pi, 0.75*pi , pi] x= 0 0.7854 1.5708 2.3562 3.1416 x is a row vector. >> y = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ] y= 0 0.7854 y is a column vector. 1.5708 2.3562 3.1416
Vectors (cont)
23
The colon notation may be used to address a block of elements. (start : increment : end)
start is the starting index, increment is the amount to add to each successive index, and end is the ending index. A shortened format (start : end) may be used if increment is 1.
Example:
>> x(1:3) ans = 0 0.7854 1.5708
Vectors
24
x= start:increment:end
length(x)
y = x dot (x, y)
t =
t =1:10
k =
1 2 3 k =2:-0.5:-1 2 1.5 1
10
0.5
-0.5
-1
x =
B
1 5
= [1:4; 5:8] 2 6 3 7 4 8
Matrices Addressing
27
Matrix Addressing:
-- matrixname(row, column) -- colon may be used in place of a row or column reference to select the entire row or column.
Example:
>> f(2,3)
ans = 6 >> h(:,1) ans = 2 1
recall: f= 1 4 h= 2 1
2 5 4 3
3 6 6 5
zeros(M,N)
MxN matrix of
zeros
ones(M,N)
rand(M,N)
Array Operations
31
Scalar-Array Mathematics For addition, subtraction, multiplication, and division of an array by a scalar simply apply the operations to all elements of the array. Example: >> f = [ 1 2; 3 4] f= 1 2 3 4 >> g = 2*f 1 Each element in the array f is g= multiplied by 2, then subtracted 1 3 by 1. 5 7
MATLAB a+b ab a .* b a ./ b a .^ b
Example:
>> x = [ 1 2 3 ]; >> y = [ 4 5 6 ]; >> z = x .* y z = 4 10 18
Transpose
Identity Matrix
B = A
eye(n) returns an n x n identity matrix eye(m,n) returns an m x n matrix with ones on the main diagonal and zeros elsewhere. C=A+B C=AB B = A, where is a scalar. C = A*B B = inv(A), A must be a square matrix in this case. rank (A) returns the rank of the matrix A. B = A.^2 squares each element in the matrix C = A * A computes A*A, and A must be a square matrix. det (A), and A must be a square matrix.
Addition and subtraction Scalar Multiplication Matrix Multiplication Matrix Inverse Matrix Powers Determinant
The input function displays a prompt string in the Command Window and then waits for the user to respond. my_val = input( Enter an input value: ); in1 = input( Enter data: ); in2 = input( Enter data: ,`s`);
Display Windows
36
Graphic (Figure) Window Displays plots and graphs Created in response to graphics commands.
M-file editor/debugger window Create and edit scripts of commands called M-files.
Plotting
37
For more information on 2-D plotting, type help graph2d Plotting a point: the function plot ()
creates a graphics window, called a Figure window, and named by default Figure No. 1
Display Facilities
39
plot(.)
Example: >>x=linspace(0,4*pi,100); >>y=sin(x); >>plot(y) >>plot(x,y)
0.7 0.6 0.5 0.4 0.3 0.2 0.1 0 -0.1 -0.2 -0.3 0 10 20 30 40 50 60 70 80 90 100
stem(.)
Example: >>stem(y) >>stem(x,y)
Display Facilities
40
title(.)
>>title(This is the sinus function)
xlabel(.)
>>xlabel(x (secs))
ylabel(.)
>>ylabel(sin(x))
MATLAB Graphs
41
x = 0:pi/100:2*pi; y = sin(x); plot(x,y) xlabel('x = 0:2\pi') ylabel('Sine of x') title('Plot of the Sine Function')
Multiple Graphs
42
Selection Programming
43
if logical expression commands end Example: (Nested) if d <50 count = count + 1; disp(d); if b>d b=0; end end Example: (else and elseif clauses) if temperature > 100 disp (Too hot equipment malfunctioning.) elseif temperature > 90 disp (Normal operating range.); elseif (Below desired operating range.) else disp (Too cold turn off equipment.) end
switch input_num case -1 input_str = 'minus one'; case 0 input_str = 'zero'; case 1 input_str = 'plus one'; case {-10,10} input_str = '+/- ten'; otherwise input_str = 'other value'; end
Loops
46
for loop
Example (for loop): for t = 1:5000 y(t) = sin (2*pi*t/10); end Example (while loop): EPS = 1; while ( 1+EPS) >1 EPS = EPS/2; end EPS = 2*EPS
the break statement break is used to terminate the execution of the loop.
M-Files
47
So far, we have discussed the execution of commands in the command window. But a more practical way is to create a M-file.
MATLAB commands. MATLAB can open and execute the commands exactly as if they were entered at the MATLAB command window. To run the M-files, just type the file name in the command window. (make sure the current working directory is set correctly) All MATLAB commands are M-files.
User-Defined Function
48
NOTE: the function_name should be the same as your file name to avoid confusion.
calling your function: -- a user-defined function is called by the name of the m-file, not the name given in the function definition. -- type in the m-file name like other pre-defined commands. Comments: -- The first few lines should be comments, as they will be displayed if help is requested for the function name. the first comment line is reference by the lookfor command.
Getting Help
50
help lists all the help topic help topic provides help for the specified topic help command provides help for the specified command
helpwin opens a separate help window for navigation lookfor keyword Search all M-files for keyword