Download presentation
Presentation is loading. Please wait.
1
Advanced MATLAB (for Electrical Engineers) Instructor: Kamran Arshad EE Club, KFUPM 28 March 2004 KFUPM
2
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.
3
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Course Syllabus First Day Introduction to MATLAB, Basics of Matrix Algebra, Iterative Calculations, Graphical Illustration Second Day Specifically deal with problems of Communication Engineering Third Day Deal with problems of Digital Signal Processing and Control Theory MINOR MODIFICATIONS MAY TAKE PLACE
4
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
5
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Why should you attend this course? Matlab used (on a daily basis) in many engineering companies
6
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)
7
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
8
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 !?
9
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
10
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
11
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Some Useful Commands whos shows the environment clear removes all variables from memory clearv1 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 c
12
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]
13
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.’
14
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Indexing Matrices Indexing using parentheses >> A(2,3) Index submatrices using vectors of 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)]
15
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
16
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Arithmetic Operations and Precedence OperationAlgebraicMatlab FormScalar additiona + ba + b subtractiona – ba – b multiplicationa x ba * b divisiona ÷ ba / b exponentiation a b a ^ b PrecedenceOperation 1Parenthesis, innermost first. 2Exponentiation, left to right 3Multiplication & division, left to right 4Addition & subtraction, left to right
17
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?
18
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, ”. ” is elementwise operation
19
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)
20
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 order 1. variable in current workspace 2. built-in variable 3. built-in m-file 4. m-file in current directory 5. m-file on search path Note: m-files can be located in current directory, or in path
21
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.m
22
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
23
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 [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.m
24
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.m
25
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Flow control - selection The if-elseif-else construction if elseif else 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
26
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Logical expressions Relational operators (compare arrays of same sizes) ==(equal to)~= (not equal) (greater than)>= (greater than or equal to) Logical operators (combinations of relational operators) &(and) |(or) ~(not) Logical functions xor isempty any all 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
27
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Flow control - repetition Repeats a code segment a fixed number of times for index= end The are executed repeatedly. At each iteration, the variable index is assigned a new value from. for k=1:12 kfac=prod(1:k); disp([num2str(k),’ ‘,num2str(kfac)]) end
28
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Example – selection and repetition function y=fact(n) % FACT – Display factorials of integers 1..n if 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..n if 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.m
29
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Flow control – conditional repetition while-loops are executed repeatedly as long as the evaluates to true while 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)]);
30
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; 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; toc tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; slow.m fast.m Loops are slow: Replace loops by vector operations!
31
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
32
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)
33
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
34
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
35
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad) Practice Using Matlab 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 !!!
36
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
37
Advanced MATLAB Course for Electrical Engineers (Kamran Arshad)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.