Advanced MATLABAdvanced MATLAB(for Electrical Engineers)(for Electrical Engineers)
Instructor: Kamran ArshadEE Club, KFUPM28 March 2004
KFUPM
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Course Information
Course Destination Course is designed for non-professionals and
engineers who wish to expand his pervious skills in using MATLAB.
Prerequisite Preliminary skills in MATLAB are required for this
course.
Syllabus Course contents and syllabus is on the consent of
instructor.
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Course Syllabus First Day
Introduction to MATLAB, Basics of Matrix Algebra, Iterative Calculations, Graphical Illustration
Second DaySpecifically deal with problems of Communication Engineering
Third DayDeal with problems of Digital Signal Processing and
Control Theory
MINOR MODIFICATIONS MAY TAKE PLACE
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
What is Matlab? A software environment for interactive numerical computations
Examples: Matrix computations and linear algebra Solving nonlinear equations Numerical solution of differential equations Statistics and data analysis Signal processing Modelling of dynamical systems Solving partial differential equations Simulation of engineering systems
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Why should you attend this course?
Matlab used (on a daily basis) in many engineering companies
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Matlab used in many courses at KFUPM
1. EE 370 Communication Engineering
2. EE 380 Control Theory
3. EE 270 Signals and Systems
Image Processing, Digital Signal Processing, and some courses at other departments of university
Why should you attend this course? (contd)
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Matlab Background
Matlab = Matrix Laboratory Originally a user interface for numerical linear algebra
routines (Lapak/Linpak) Commercialized 1984 by The Mathworks Since then heavily extended (defacto-standard) Higher-level, similar to ‘C’ programming environment;
no compiler 2D (rectangular & polar) and 3D display of data,
functions, system responses
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Iterative Calculations
Matlab is interactive, no need to declare variables >> 2+3*4/2 >> a=5e-3; b=1; a+b
Most elementary functions and constants are already defined
>> cos(pi) >> abs(1+i) >> sin(pi)
Last call gives answer 1.2246e-016 !?
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Variable and Memory Management
Matlab uses double precision (approx. 16 significant digits)>> format long>> format compact
(see all other formats by typing help format on command prompt)
All variables are shown with>> who>> whos
Variables can be stored on file>> save filename>> clear>> load filename
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
The Help System
Search for appropriate function>> lookfor keyword
Rapid help with syntax and function definition >> help function
An advanced hyperlinked help system is launched by>> helpdesk
Complete manuals as PDF files
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Some Useful Commands
whos shows the environment clear removes all variables from memory clear v1 ez removes variables v1 & ez from memory clf clears the current figure or graph clc clears the command window dir lists current directory delete fname deletes file named fname help matlab\general General purpose commands help matlab\ops Operators and special characters help matlab\lang Programming language
constructs help matlab\elmat Elementary matrices help matlab\elfun Elementary math functions
To abort type ctrl cTo abort type ctrl c
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Vectors and Matrices
Vectors (arrays) are defined as >> v = [1, 2, 4, 5] >> w = [1; 2; 4; 5]
Matrices (2D arrays) defined similarly >> A = [1,2,3;4,-5,6;5,-6,7]
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Matrix Operators
All common operators are overloaded>> v + 2
Common operators are available>> B = A’>> A*B>> A+B
Note: Matlab is case-sensitive
A and a are two different variables• Transponate conjugates complex entries; avoided by
>> B=A.’
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Indexing Matrices
Indexing using parentheses>> A(2,3)
Index submatrices using vectorsof row and column indices >> A([2 3],[1 2])
Ordering of indices is important!>> B=A([3 2],[2 1])>> B=[A(3,2),A(3,1); A(2,2);A(2,1)]
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Indexing Matrices(Cond)
Index complete row or column using the colon operator >> A(1,:)
Can also add limit index range>> A(1:2,:)>> A([1 2],:)
General notation for colon operator>> v=1:5>> w=1:2:5
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Arithmetic Operations and Precedence
Operation Algebraic Matlab Form Scalar
addition a + b a + bsubtraction a – b a – bmultiplication a x b a * bdivision a ÷ b a / bexponentiation ab a ^ b
Precedence Operation
1 Parenthesis, innermost first.
2 Exponentiation, left to right
3 Multiplication & division, left to right
4 Addition & subtraction, left to right
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Precedence - Example
% Compute the area of the trapezoid » base = 5 » height_1 = 3 » height_2 = 7 » area = 0.5*base*(height_1 + height_2) % What is the area?
» area = 0.5*base*height_1 + height_2 % What is the area?
% Where are the parentheses assumed?
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Matrix Functions Many elementary matrices predefined
>> help elmat;>> I=eye(3)
Elementary functions are often overloaded>> help elmat>> sin(A)
Specialized matrix functions and operators>> As=sqrtm(A)>> As^2>> A.*A
Note: in general, ”.<operator>” is elementwise operation
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Numerical Linear Algebra
Basic numerical linear algebra>> z=[1;2;3]; x=inv(A)*z>> x=A\z
Many standard functions predefined>> det(A)>> rank(A)>> eig(A)
The number of input/output arguments can often be varied>> [V,D]=eig(A)
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
The programming environment
Matlab can’t tell if identifier is variable or function >> z=theta;
Matlab searches for identifier in the following order1. variable in current workspace2. built-in variable3. built-in m-file4. m-file in current directory5. m-file on search path
Note: m-files can be located in current directory, or in path
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Script files
Script-files contain a sequence of Matlab commands
Executed by typing its name>> factscript
Operates on variables in global workspace Variable n must exist in workspace Variable y is created (or over-written)
Use comment lines (starting with %) to document file
%FACTSCRIPT – Compute n-factorial, n!=1*2*...*n
y = prod(1:n);
%FACTSCRIPT – Compute n-factorial, n!=1*2*...*n
y = prod(1:n);
factscript.mfactscript.m
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Displaying code and getting help
To list code, use type command >> type factscript
The help command displays first consecutive comment lines
>> help factscript
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Functions
Functions describe subprograms Take inputs, generate outputs Have local variables (invisible in global
workspace)[output_arguments]= function_name(input_arguments)
% Comment lines <function body>
function [z]=factfun(n)% FACTFUN – Compute factorial% Z=FACTFUN(N)
z = prod(1:n);
function [z]=factfun(n)% FACTFUN – Compute factorial% Z=FACTFUN(N)
z = prod(1:n);
factfun.mfactfun.m
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Scripts or function: when use what?
Functions Take inputs, generate outputs, have internal
variables Solve general problem for arbitrary parameters
Scripts Operate on global workspace Document work, design experiment or test Solve a very specific problem once
% FACTTEST – Test factfun
N=50;y=factfun(N);
% FACTTEST – Test factfun
N=50;y=factfun(N);
facttest.mfacttest.m
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Flow control - selection
The if-elseif-else constructionif <logical expression>
<commands>
elseif <logical expression>
<commands>
else
<commands>
end
if height>170
disp(’tall’)
elseif height<150
disp(’small’)
else
disp(’average’)
end
if height>170
disp(’tall’)
elseif height<150
disp(’small’)
else
disp(’average’)
end
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Logical expressions Relational operators (compare arrays of same sizes)
== (equal to) ~= (not equal) < (less than) <= (less than or equal to)> (greater than) >= (greater than or equal to)
Logical operators (combinations of relational operators)& (and)| (or)~ (not)
Logical functionsxorisemptyanyall
if (x>=0) & (x<=10)
disp(‘x is in range [0,10]’)
else
disp(‘x is out of range’)
end
if (x>=0) & (x<=10)
disp(‘x is in range [0,10]’)
else
disp(‘x is out of range’)
end
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Flow control - repetition
Repeats a code segment a fixed number of timesfor index=<vector>
<statements>
end
The <statements> are executed repeatedly.At each iteration, the variable index is assigneda new value from <vector>.
for k=1:12 kfac=prod(1:k); disp([num2str(k),’ ‘,num2str(kfac)])end
for k=1:12 kfac=prod(1:k); disp([num2str(k),’ ‘,num2str(kfac)])end
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Example – selection and repetition
function y=fact(n)% FACT – Display factorials of integers 1..nif nargin < 1 error(’No input argument assigned’)elseif n < 0 error(’Input must be non-negative’)elseif abs(n-round(n)) > eps error(’Input must be an integer’)end
for k=1:n kfac=prod(1:k);
disp([num2str(k),’ ’,num2str(kfac)])
y(k)=kfac;
end;
function y=fact(n)% FACT – Display factorials of integers 1..nif nargin < 1 error(’No input argument assigned’)elseif n < 0 error(’Input must be non-negative’)elseif abs(n-round(n)) > eps error(’Input must be an integer’)end
for k=1:n kfac=prod(1:k);
disp([num2str(k),’ ’,num2str(kfac)])
y(k)=kfac;
end;
fact.mfact.m
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Flow control – conditional repetition
while-loops
<statements> are executed repeatedly as long as the <logical expression> evaluates to true
while <logical expression>
<statements>
end
k=1;
while prod(1:k)~=Inf,
k=k+1;
end
disp([‘Largest factorial in Matlab:’,num2str(k-1)]);
k=1;
while prod(1:k)~=Inf,
k=k+1;
end
disp([‘Largest factorial in Matlab:’,num2str(k-1)]);
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Programming tips and tricks
Programming style has huge influence on program speed!
tic; X=-250:0.1:250;for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end;end;toc
tic; X=-250:0.1:250;for ii=1:length(x) if x(ii)>=0, s(ii)=sqrt(x(ii)); else s(ii)=0; end;end;toc
ticx=-250:0.1:250;s=sqrt(x); s(x<0)=0;toc;
ticx=-250:0.1:250;s=sqrt(x); s(x<0)=0;toc;
slow.mslow.m
fast.mfast.m
Loops are slow: Replace loops by vector operations!
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
MATLAB Graphics
MATLAB also provides a powerful set of graphics commands to create and manipulate graphics
Many commands can be entered from the Figure window
Advanced commands must be entered from the Command window or a script
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Graphics
Visualization of vector data is available>> x=-pi:0.1:pi; y=sin(x);>> plot(x,y)>> plot(x,y,’s-’)>> xlabel(’x’); ylabel(’y=sin(x)’);
Can change plot properties in Figure menu, >> h=plot(x,y); set(h, ’LineWidth’, 4);
Many other plot functions available>> v=1:4; pie(v)
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Graphics
Three-dimensional graphics>> A = zeros(32);>> A(14:16,14:16) = ones(3);>> F=abs(fft2(A));>> subplot(211),mesh(A);>> subplot(212),mesh(F);>> rotate3d on % Turn on mouse based movement
Several other plot functions available >> surfl(F)
Can change lightning and material properties>> cameramenu>> material metal
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Practice Using Matlab
MatLab >>numerator = x^3 - 2*x^2 + 6.3; >>denominator = x^2 + 0.05005x – 3.14; >>f = numerator / denominator
Advice Use several statements … easier to debug … will
save you time. Use parenthesis … do not rely on precedence rules
3 2
2
2 6.3
0.05005 3.14
x x xf
x x
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Practice Using Matlab2
2
0
4
2
ax bx c
b b acx
a
Calculate roots of quadratic equation .
Advice Take as input the values of a, b and c. Apply check for different type of roots, and calculate
roots. Print out the values of roots on the screen !!!
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Summary
Lecture Understand the
MATLAB environment Understand various
commands of MTALAB Run small MATLAB
segments Graph data Summary
Action Items Review the lecture Record what you
learned and how this relates to your Learning Objectives for this class
Explore MATLAB. Practice commands Come prepared to ask
questions about MATLAB
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)