1 / 37

Advanced MATLAB (for Electrical Engineers)

Advanced MATLAB (for Electrical Engineers). Instructor: Kamran Arshad EE Club, KFUPM 28 March 2004 KFUPM. Course Information. Course Destination Course is designed for non-professionals and engineers who wish to expand his pervious skills in using MATLAB. Prerequisite

allie
Download Presentation

Advanced MATLAB (for Electrical Engineers)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Advanced MATLAB(for Electrical Engineers) Instructor: Kamran Arshad EE Club, KFUPM 28 March 2004 KFUPM

  2. 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. 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. 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. Why should you attend this course? • Matlab used (on a daily basis) in many engineering companies

  6. Why should you attend this course? (contd) • Matlab used in many courses at KFUPM • EE 370 Communication Engineering • EE 380 Control Theory • EE 270 Signals and Systems • Image Processing, Digital Signal Processing, and some courses at other departments of university

  7. 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. 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. 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. 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. Some Useful Commands • whosshows the environment • clearremoves all variables from memory • clearv1 ezremoves variables v1 & ez from memory • clfclears the current figure or graph • clc clears the command window • dirlists current directory • delete fnamedeletes file named fname • help matlab\generalGeneral purpose commands • help matlab\opsOperators and special characters • help matlab\langProgramming language constructs • help matlab\elmatElementary matrices • help matlab\elfunElementary math functions To abort type ctrl c

  12. 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. 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. 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)]

  15. 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. 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 Arithmetic Operations and Precedence

  17. 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. 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

  19. 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. 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. factscript.m %FACTSCRIPT – Compute n-factorial, n!=1*2*...*n y = prod(1:n); Script files • Script-files contain a sequence of Matlab commands • Executed by typing its name >> factscript • Operates on variables in global workspace • Variablen must exist in workspace • Variable yis created (or over-written) • Use comment lines (starting with %) to document file

  22. Displaying code and getting help • To list code, use type command • >> type factscript • The help command displays first consecutive comment lines • >> help factscript

  23. factfun.m function [z]=factfun(n)% FACTFUN – Compute factorial% Z=FACTFUN(N) z = prod(1:n); 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>

  24. facttest.m % FACTTEST – Test factfun N=50;y=factfun(N); 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

  25. Flow control - selection • The if-elseif-else construction if <logical expression> <commands> elseif <logical expression> <commands> else <commands> end if height>170 disp(’tall’) elseif height<150 disp(’small’) else disp(’average’) end

  26. 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 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

  27. Flow control - repetition • Repeats a code segment a fixed number of times for 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

  28. fact.m 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; Example – selection and repetition

  29. while <logical expression> <statements> end <statements> are executed repeatedly as long as the <logical expression> evaluates to true k=1; while prod(1:k)~=Inf, k=k+1; end disp([‘Largest factorial in Matlab:’,num2str(k-1)]); Flow control – conditional repetition • while-loops

  30. slow.m 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 fast.m tic x=-250:0.1:250; s=sqrt(x); s(x<0)=0; toc; Programming tips and tricks • Programming style has huge influence on program speed! Loops are slow: Replace loops by vector operations!

  31. 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. 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. 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. 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. 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. 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 Summary

  37. Thank U

More Related