Docsity

Introduction to Matlab, Study notes of Electrical and Electronics Engineering

Partial preview of the text

Download Introduction to Matlab and more Study notes Electrical and Electronics Engineering in PDF only on Docsity!

Introduction to MATLAB Introduction: What is MATLAB? MATLAB is a high-level technical computing language equipped with a user-friendly interface. Its name stems from the words Matrix and Laboratory as it is based on the use of matrices. MATLAB is an extremely powerful too! useful for scientists and engineers from various disciplines. For example, MATLAB can be used in a wide range of applications, such as telecommunications, signal and image processing, control, mathematics, financial modeling, bioengineering, aeronautics, and many more. M-Files In order to write many commands that are executed all together, the program must be written in a text editor. In this editor, one can type all the needed commands to form a program, save the program, and execute it any time he or she wants. The text files are called M-files due to their suffice xm. There are two categories of M-files: the Scripts and the Functions. Scripts Scripts are the M-files with MATLAB commands. Their name must have a .m suffix. Scripts are suitable for solving the problems that require many commands. The advantage of the scripts is that they are implemented very easily. Functions Function is also M-files, That is, is files with extension .n1 and must be saved in the current Directory of MATLAB. The difference between functions and scripts is that a function accepts one or more input arguments and returns one or more output arguments. To declare that an M-file is a function the first line of the m file must contain the syntax definition. More specifically, the first line of the M-file must be of the form function [y1,y2,y3, ...yn]=name{x1,x2,x3... xm}. The variable y1,y2,...yn are the outputs of the function while x7,x2,...xm are the input arguments. In case there is only one output, the square brackets are not necessary. The “name” specifies the name of the function. In order to execute a function, first the M-File is saved in Current Directory Command Window and Command History Command Window: Use the Command Window to enter variables and to run functions and M-file scripts. Press the up arrow key to recall a statement previously typed. Edit the statement as needed and then press Enter to run it. Command History: Statements entered in the Command Window are logged in the Command History. From the Command History, previously run statements can be viewed, copied and executed. M-file can be created from selected statements. (ii) Current Directory Browser and Search Path: MATLAB file operations use the current directory and the search path as reference points. Any file required to run must either be in the current directory or on the search path. (iii) Workspace Browser and Array Editor: The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. The variables can be added to the workspace by using functions, running M-files, and loading saved workspaces. To delete variables from the workspace, select the variables and select Edit > Delete. Array Editor: Double-click a variable in the Workspace browser, or use open var variable name, to see it in the Array Editor. Use the Array Editor to view and edit a visual representation of variables in the workspace. (iv) Editor/Debugger: Editor/Debugger is used to create and debug M-files, which are programs to run MATLAB functions. The Editor/Debugger provides a graphical User interface for text editing, as well as for M-file debugging. To create or edit an M-file use File > New or File > Open, or use the edit function. The important commands/ functions are as below: 1. cle (Remove items from workspace, freeing up system memory) clears all input and output from the Command Window display, giving "clean screen." After using clc, the scroll bar cannot be used to see the history of functions, but still the up arrow can be used to recall statements from the command history. 2. Close (Remove specified figure): close deletes the current figure or the specified figure(s). It optionally returns the status of the close operation. 3. xlabel, ylabel, zlabel (Label x-, y-, and z-axis) : Each axes graphics object can have one label for the x-, y-, and z-axis. The label appears beneath its respective axis in a two-dimensional plot and to the side or beneath the axis in a three-dimensional plot. xlabel('string') labels the x-axis of the current axes. ylabel(...) and zlabel(...) label the y-axis and z-axis, respectively, of the current axes. 4. title ( Add title to current axes) : Each axes graphics object can have one title. The title is located at the top and in the center of the axes. user entry = input('prompt') Displays prompt as a prompt on the screen, waits for input from the keyboard, and returns the value entered in user entry. User entry = input (‘prompt'’s’) returns the entered string as a text variable rather than as a variable name or numerical value. 11. zeros (Create array of all zeros) : B = zeros(n) Returns an n-by-n matrix of zeros. An error message appears if n is not a scalar. 12. ones (Create array of all ones) : Y = ones(n) Rreturns an n-by-n matrix of 1s. An error message appears if n is nota scalar. 13. exp (Exponential) : Y=exp(X) The exp function is an elementary function that operates element-wise on arrays. Its domain includes complex numbers. Y = exp(X) returns the exponential for each element of X. 14. disp (Display text or array) : disp(X) Displays an array, without printing the array name. If X contains a text string, the string is displayed. Another way to display an array on the screen is to type its name, but this prints a leading "X=," which is not always desirable. Note that disp does not display empty arrays. 15. conv (Convolution and polynomial multiplication) : w =conv(u,v) convolves vectors u and v. Algebraically, convolution is the same operation as multiplying the polynomials whose coefficients are the elements of u and v. 16. xcorr (Cross-correlation) : c=xcorr(x,y) returns the cross-correlation sequence in a length 2*N-1 vector, where x and y are length N vectors (N>1). If x and y are not the same length, the shorter vector is zero-padded to the length of the longer vector. 17. filter (1-D digital filter) : y = filter(b,a,X) _ filters the data in vector X with the filter described by numerator coefficient vector b and denominator coefficient vector a. If a(1) is not equal to 1, filter normalizes the filter coefficients by a(1). If a(1) equals 0, filter returns an error. 18. poly (Polynomial with specified roots) : r=roots(p) which returns a column vector whose elements are the roots of the polynomial specified by the coefficients row vector p. For vectors, roots and poly are inverse functions of each other, up to ordering, scaling, and round off error. 21. abs (Absolute value and complex magnitude) : abs(X) returns an array Y such that each element of Y is the absolute value of the corresponding element of X. 22. fft (Discrete Fourier transform) : Y = fft(X) Y = fft(X) returns the discrete Fourier transform (DFT) of vector X, computed with a fast Fourier transform (FFT) algorithm. 23. mod (Modulus after division) : M=mod(X,Y) returns X - n.*Y where n = floor(x./Y). If Y is not an integer and the quotient X./Y is within round off error of an integer, then n is that integer. The inputs X and Y must be real arrays of the same size, or real scalars. 24. sqrt (Square root) : B = sqrt(X) returns the square root of each element of the array X. For the elements of X that are negative or complex, sart(X) produces complex results. 28. fliplr (Flip matrix left to right) : B=flipir(A) returns A with columns flipped in the left-right direction, that is, about a vertical axis. If A is a row vector, then flipir(A) returns a vector of the same length with the order of its elements reversed. If A is a column vector, then flipIr(A) simply returns A. 29. min (Smallest elements in array) : C=min(A) returns the smallest elements along different dimensions of an array. If A isa vector, min (A) returns the smallest element in A. If A is a matrix, min(A) treats the columns of A as vectors, returning a row vector containing the minimum element from each column. If A is a multidimensional array, min operates along the first no singleton dimension. 30. max ( Largest elements in array) : C=max(A) returns the largest elements along different dimensions of an array. If Ais a vector, max(A) returns the largest element in A.If A is a matrix, max(A) treats the columns of Aas vectors, returning a row vector containing the maximum element from each column. If A is a multidimensional array, max(A) treats the values along the first non-singleton dimension as vectors, returning the maximum value of each vector. 31. find (Find indices and values of nonzero elements) : ind = find(X) locates all nonzero elements of array X, and returns the linear indices of those elements in vector ind. If X is a row vector, then ind is a row vector; otherwise, ind is a column vector. If X contains no nonzero elements or is an empty array, then ind is an empty array. 32. residuez (z-transform partial-fraction expansion ) : median (a) sort (a) sort(a, ‘descend’ ) ans = 3.8000 %Mean value of the elements. ans = 4 ‘% Median value of the vector. ans=0 2 4 6 7 s Sorting in ascending order. ans=7 6 4 2 0 %Sorting in descending order. Familiarisation of MATLAB 19 2. Performing numerical calculations MATLAB can be used as a calculator to do arithmetic and logic operations. Let A and B be two matrices or vectors or scalar quantities. The basic arithmetic operators used in MATLAB are given in Table 1.2. Table 1.2 Operators in MATLAB + : A+B Arithmetic addition between A and B. = : A-B Arithmetic subtraction between A and B. * : A*B Multiplication between A and B, / —: A/B Division between A and B. . : A°k Computes A*, A and k are scalars. A.*B Element-wise multiplication between A and B. A./B Element-wise division between A and B. -* : A.7°k Element-wise kth power of matrix or array A, k is a scalar Some examples of using Command Window in performing numerical computations are given as follows. Example 1: Addition of scalar quantities >> A=4; >> B=7; >> C=A+B C= 41 Example 2: Addition of matrices >> A=[1 2331014; 21 4]; >> B=[1 13;0 5 7; 27 4]; >> C=A+B C= be a oo Example 6: Element-by-element multiplication of matrices >> A=[1 2 3;1 01; 21 4]; >> B=[1 1 3;05 7; 27 4]; >> C=A.*B Cs a 2 9 0 0 7 4 7 16 Example 7: Computation of 23(4 — 3 *5) + 34(—4 + 6/3) >> 2° (3)* (4-345) +37 (4) * (-4+6/3) ans = -250 In this manner, we can perform all types of numerical calculations by using appropriate arithmetic operators and statements in the MATLAB Command Window. 3. Running functions and other M-files The Command Window can be used to run MATLAB built-in or user defined functions and other M-files. The general syntax to run (eall) functions in Command Window is given below. >> [output_1, output_2] = function name(input_1, input_2) In the above syntax, the function with function name function_name has been called. The function accepts two input arguments, input_1 and input_2, whereas it produces two outputs which are assigned to two output arguments output_1 and output_2. To display outputs in Command Window, press ‘Enter’ after the above statement. This is the syntax for running (calling) both the built-in and user-defined functions. It is not required to use square brackets if there is only one output argument or if the function returns only one output. We can run functions with any number of input or output arguments in the Command Window. Some examples of running the built-in functions in Command Window are as follows Example 1: Square root of a number using ‘sqrt’ function >> a=sqrt (49) Example 2: Logarithmic and exponential functions >> a=log(100) % logarithm with base ‘e’. as 4.6052 >> b=logi0(100) % logarithm with base 10. be 2 >> a=exp(2) as 7.3891 >> a=exp(-4) 0.0183 Example 3: Trigonometric functions >> a=cos(2*pi) % Input argument is in radian. a= 1 >> b=esin(pi/3) b= 0.8660 >> c=tan(2*pi/3) e- -1.7321 >> b=acos(0.5) % inverse cosine function, output in radian b= 1.0472 Example 4: Matrix and array functions >> A=ones(3) 4% Create a matrix of all ones.