# INTRODUCTION TO Mat Lab and Simulink MATLAB matrix

INTRODUCTION TO Mat. Lab and Simulink

MATLAB - matrix laboratory - Developed by a lecturer in 1970’s to help students learn linear algebra. - marketed and further developed under Math. Works Inc. - used for matrix based manipulation, plotting functions and data, implementation of algorithms, creation of user interface(GUI) - Available in many operating systems – Windows, Macintosh, Unix, DOS - provides interface with other language C, C++, FORTRAN and Java. - several toolboxes to solve specific problems - First Version 1. 0 in 1984 - Latest version R 2012 b in September 2012

MATLAB Workspace To get help Current Directory Command history Work Space Current Directory Command window

MATLAB Workspace – Array Editor Row headings Tabs to change between different variables Column headings

Mat. Lab Applications - Mathematics - Data Analysis - Programming and Data Types - File Input/output operations - Graphics - 3 -D Visualization - GUI Design - External Interfaces www. Vidyarthiplus. com

Operators + Addition + Unary plus - Subtraction - Unary minus * Matrix multiplication ^ Matrix power Back slash or left matrix divide / Slash or right matrix divide ’ Transpose . ’ Non conjugated transpose . * Array multiplication (element-wise) . ^ Array power (element-wise) . Left array divide(element-wise) . / Right array divide(element-wise) www. Vidyarthiplus. com

Basic Commands pwd – print working directory – prints current working directory path – view or change Matlab search directory work path clf – open empty figure window shg – show graphics, when the command window hides the figure window Clc – clears command window whos - WHOS List current variables, long form. WHOS is a long form of WHO. It lists all the variables in the current workspace, together with information about their size, bytes, class, etc. who – list current variables list. exit – terminates Matlab quit – Quits Matlab same as exit home – move cursor to upper left corner of the command window help – help for matlab functions in command window. clear – clears workspace and frees system memory cd – change directory dir – directory listing www. Vidyarthiplus. com

Basic Commands edit – edit or create M-file license – returns license number ver – version information for Math works products version – displays version of Matlab linspace – generates linearly spaced vectors meshgrid – generates X and Y arrays for 3 -D plots ones- generates array of all ones zeros – creates array of all zeros www. Vidyarthiplus. com

Variables Vectors and Matrices ALL variables are matrices e. g. 1 x 1 4 x 1 1 x 4 Variables are stored in workspace Variables • They are case–sensitive i. e. x X • Their names can contain up to 31 characters • Must start with a letter www. Vidyarthiplus. com 2 x 4

Vectors and Matrices • How do we assign a value to a variable? >>> v 1=3 v 1 = >>> whos Name Size R 1 x 1 8 double array >>> i 1=4 i 1 1 x 1 8 double array i 1 = v 1 1 x 1 8 double array 3 4 >>> who R= Your variables are: >>> Class Grand total is 3 elements using 24 bytes >>> R=v 1/i 1 0. 7500 Bytes R >>> i 1 v 1

Vectors and Matrices • How do we assign values to vectors? >>> A = [1 2 3 4 5] A = 1 2 3 4 5 >>> A row vector – values are separated by spaces >>> B = [10; 12; 14; 16; 18] B = 10 12 14 16 18 >>> A column vector – values are separated by semi–colon (; )

Vectors and Matrices • How do we assign values to vectors? If we want to construct a vector of, say, 100 elements between 0 and 2 – linspace >>> c 1 = linspace(0, (2*pi), 100); >>> whos Name Size c 1 1 x 100 Bytes 800 Class double array Grand total is 100 elements using 800 bytes >>>

Vectors and Matrices • How do we assign values to vectors? If we want to construct an array of, say, 100 elements between 0 and 2 – colon notation >>> c 2 = (0: 0. 0201: 2)*pi; >>> whos Name Size Bytes Class c 1 1 x 100 800 double array c 2 1 x 100 800 double array Grand total is 200 elements using 1600 bytes >>> www. Vidyarthiplus. com

Vectors and Matrices • How do we assign values to matrices ? >>> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >>> • Columns separated by space or a comma • Rows separated by semi-colon www. Vidyarthiplus. com

Vectors and Matrices • How do we access elements in a matrix or a vector? Try the followings: >>> A(: , 3) ans = 3 6 9 >>> A(2, 3) ans = 6 >>> A(1, : ) ans = 1 2 3 >>> A(2, : ) ans = 4 5 www. Vidyarthiplus. com 6

Vectors and Matrices • Some special variables Beep – turns on/off beep sound >>> 1/0 pi ( ) ans = inf (e. g. 1/0) Warning: Divide by zero. Inf >>> pi ans = 3. 1416 >>> i ans = 0+ 1. 0000 i www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Performing operations to every entry in a matrix >>> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >>> Add and subtract >>> A+3 ans = 4 7 10 5 8 11 6 9 12 >>> A-2 ans = -1 2 5 0 3 6 1 4 7 www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Performing operations to every entry in a matrix >>> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >>> Multiply and divide >>> A*2 ans = 2 8 14 >>> A/3 ans = 0. 3333 1. 3333 2. 3333 4 10 16 www. Vidyarthiplus. com 6 12 18 0. 6667 1. 6667 2. 6667 1. 0000 2. 0000 3. 0000

Vectors and Matrices • Arithmetic operations – Matrices Performing operations to every entry in a matrix >>> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 >>> A^2 = A * A Power To square every element in A, use the element –wise operator. ^ >>> A. ^2 ans = 1 16 49 >>> A^2 ans = 30 66 102 www. Vidyarthiplus. com 4 25 64 9 36 81 126 42 96 150

Vectors and Matrices • Arithmetic operations – Matrices Performing operations between matrices >>> A=[1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 A*B A. *B >>> B=[1 1 1; 2 2 2; 3 3 3] B = 1 1 1 2 2 2 3 3 3 = = www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Performing operations between matrices A/B ? (matrices singular) A. /B = www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Performing operations between matrices A^B ? ? ? Error using ==> ^ At least one operand must be scalar A. ^B = www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Example: Solve the below circuit for V 1 and V 2. -j 5 10 j 10 2 -90 o 1. 5 0 o www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Example (cont) (0. 1 + j 0. 2)V 1 – j 0. 2 V 2 - j 0. 2 V 1 + j 0. 1 V 2 = -j 2 = 1. 5 = A x = www. Vidyarthiplus. com y

Vectors and Matrices • Arithmetic operations – Matrices Example (cont) >>> A=[(0. 1+0. 2 j) -0. 2 j; -0. 2 j 0. 1 j] A = 0. 1000+ 0. 2000 i 0 - 0. 2000 i 0+ 0. 1000 i >>> y=[-2 j; 1. 5] y = 0 - 2. 0000 i 1. 5000 >>> x=Ay * AB is the matrix division of A into B, which is x = roughly the same as INV(A)*B * 14. 0000+ 8. 0000 i 28. 0000+ 1. 0000 i >>> www. Vidyarthiplus. com

Vectors and Matrices • Arithmetic operations – Matrices Example (cont) >>> V 1= abs(x(1, : )) V 1 = 16. 1245 >>> V 1 ang= angle(x(1, : )) V 1 ang = 0. 5191 V 1 = 16. 12 29. 7 o V www. Vidyarthiplus. com

Built in functions (commands) Scalar functions – used for scalars and operate element-wise when applied to a matrix or vector e. g. sin cos tan asin abs angle sqrt round floor log At any time you can use the command help to get help e. g. >>>help sin www. Vidyarthiplus. com

Built in functions (commands) >>> a=linspace(0, (2*pi), 10) a = Columns 1 through 7 0 0. 6981 1. 3963 2. 0944 2. 7925 3. 4907 4. 1888 Columns 8 through 10 4. 8869 5. 5851 >>> b=sin(a) 6. 2832 b = Columns 1 through 7 0 0. 6428 0. 9848 0. 8660 -0. 8660 Columns 8 through 10 -0. 9848 -0. 6428 0. 0000 >>> www. Vidyarthiplus. com 0. 3420 -0. 3420

Built in functions (commands) Vector functions – operate on vectors returning scalar value e. g. max min mean prod sum length >>> a=linspace(0, (2*pi), 10); >>> max(b) >>> b=sin(a); ans = 0. 9848 >>> max(a) ans = 6. 2832 >>> length(a) ans = 10 >>> www. Vidyarthiplus. com

Built in functions (commands) Matrix functions – perform operations on matrices >>> help elmat >>> help matfun e. g. eye size inv det eig At any time you can use the command help to get help www. Vidyarthiplus. com

Built in functions (commands) Matrix functions – perform operations on matrices >>> x=rand(4, 4) >>> x*xinv x= 0. 9501 0. 8913 0. 8214 0. 9218 0. 2311 0. 7621 0. 4447 0. 7382 0. 6068 0. 4565 0. 6154 0. 1763 1. 0000 0. 4860 0. 0185 0. 7919 0. 4057 0 1. 0000 0 0. 0000 0 1. 0000 0 0 0. 0000 1. 0000 >>> xinv=inv(x) ans = xinv = 2. 2631 -2. 3495 -0. 4696 -0. 6631 -0. 7620 1. 2122 1. 7041 -1. 2146 -2. 0408 1. 4228 1. 5538 1. 3730 1. 3075 -0. 0183 -2. 5483 0. 6344 >>> www. Vidyarthiplus. com

Built in functions (commands) From our previous example, = A x = >>> x=inv(A)*y x = 14. 0000+ 8. 0000 i 28. 0000+ 1. 0000 i www. Vidyarthiplus. com y

Built in functions (commands) Data visualization – plotting graphs >>> help graph 2 d >>> help graph 3 d e. g. plot polar semilog plotyy loglog mesh surf www. Vidyarthiplus. com

Built in functions (commands) eg 1_plt. m Data visualization – plotting graphs Example on plot – 2 dimensional plot >>> x=linspace(0, (2*pi), 100); >>> y 1=sin(x); Add title, labels and legend >>> y 2=cos(x); title >>> plot(x, y 1, 'r-') >>> hold xlabel ylabel legend Use ‘copy’ and ‘paste’ to add to your window–based document, e. g. MSword Current plot held >>> plot(x, y 2, 'g--') >>> www. Vidyarthiplus. com

Built in functions (commands) Data visualization – plotting graphs Example on plot – 2 dimensional plot www. Vidyarthiplus. com eg 1_plt. m

Built in functions (commands) eg 2_srf. m Data visualisation – plotting graphs Example on mesh and surf – 3 dimensional plot Supposed we want to visualize a function Z = 10 e(– 0. 4 a) sin (2 ft) for f = 2 when a and t are varied from 0. 1 to 7 and 0. 1 to 2, respectively >>> [t, a] = meshgrid(0. 1: . 01: 2, 0. 1: 0. 5: 7); >>> f=2; >>> Z = 10. *exp(-a. *0. 4). *sin(2*pi. *t. *f); >>> surf(Z); >>> figure(2); >>> mesh(Z); www. Vidyarthiplus. com

Built in functions (commands) Data visualization – plotting graphs Example on mesh and surf – 3 dimensional plot www. Vidyarthiplus. com eg 2_srf. m

M-files : Script and function files When problems become complicated and require re–evaluation, entering command at MATLAB prompt is not practical Solution : use M-files Script Function Collections of commands executed in sequence when called saved with extension “. m” User defined commands normally has input and output saved with extension “. m” www. Vidyarthiplus. com

M-files : script and function files (script) At Matlab prompt type in edit to invoke M-file editor Save this file as test 1. m www. Vidyarthiplus. com

M-files : script and function files (script) To run the M-file, type in the name of the file at the prompt e. g. >>> test 1 It will be executed provided that the saved file is in the known path Type in matlabpath to check the list of directories listed in the path Use path editor to add the path: File Set path … www. Vidyarthiplus. com

M-files : script and function files (script) www. Vidyarthiplus. com

M-files : script and function files (script) Example – RLC circuit R = 10 C + L V – Exercise 1: Write an m–file to plot Z, Xc and XL versus frequency for R =10, C = 100 u. F, and L = 0. 01 H. www. Vidyarthiplus. com

M-files : script and function files (script) Example – RLC circuit Total impedance is given by: When www. Vidyarthiplus. com

M-files : script and function files (script) Example – RLC circuit www. Vidyarthiplus. com

M-files : script and function files (script) eg 6. m Example – RLC circuit R = 10 C + V L – For a given values of C and L, plot the following versus the frequency a) the total impedance , b) Xc and XL c) phase angle of the total impedance for 100 < < 2000 www. Vidyarthiplus. com

M-files : script and function files (script) Example – RLC circuit www. Vidyarthiplus. com eg 6. m

M-files : script and function files (function) • Function is a ‘black box’ that communicates with workspace through input and output variables. INPUT FUNCTION – Commands – Functions – Intermediate variables www. Vidyarthiplus. com OUTPUT

M-files : script and function files (function) Every function must begin with a header: function output=function_name(inputs) Output variable Must match the file name input variable www. Vidyarthiplus. com

M-files : script and function files (function) • Function – a simple example function y=react_C(c, f) %react_C calculates the reactance of a capacitor. %The inputs are: capacitor value and frequency in hz %The output is 1/(w. C) and angular frequency in rad/s y(1)=2*pi*f; w=y(1); y(2)=1/(w*c); File must be saved to a known path with filename the same as the function name and with an extension ‘. m’ Call function by its name and arguments help react_C will display comments after the header www. Vidyarthiplus. com

M-files : script and function files (function) • impedance. m Function – a more realistic example function x=impedance(r, c, l, w) %IMPEDANCE calculates Xc, Xl and Z(magnitude) and %Z(angle) of the RLC connected in series %IMPEDANCE(R, C, L, W) returns Xc, Xl and Z (mag) and %Z(angle) at W rad/s %Used as an example for IEEE student, UTM %introductory course on MATLAB if nargin <4 error('not enough input arguments') end; x(1) = 1/(w*c); x(2) = w*l; Zt = r + (x(2) - x(1))*i; x(3) = abs(Zt); x(4)= angle(Zt); www. Vidyarthiplus. com

M-files : script and function files (function) eg 7_fun. m We can now add our function to a script M-file R=input('Enter R: '); C=input('Enter C: '); L=input('Enter L: '); w=input('Enter w: '); y=impedance(R, C, L, w); fprintf('n The magnitude of the impedance at %. 1 f rad/s is %. 3 f ohmn', w, y(3)); fprintf('n The angle of the impedance at %. 1 f rad/s is %. 3 f degreesnn', w, y(4)); www. Vidyarthiplus. com

Simulink

Simulink – Model, analyze and simulate – – dynamic systems using block diagrams. Fully integrated with MATLAB , easy and fast to learn and flexible. Simulate linear, non–linear or discrete systems. C codes can be generated from Simulink models for embedded applications and rapid prototyping. Various simulation toolboxes for wide engineering applications However modeling a system is not necessarily easy !!!!!

Simulink Model – simplified representation of a system – e. g. using mathematical equation We simulate a model to study the behavior of a system – need to verify that our model is correct – expect results Knowing how to use Simulink or MATLAB does not mean that you know how to model a system www. Vidyarthiplus. com

Typical Model of Simulink - Includes Sources, Systems and Sinks Sources - Random Signals - Function Generator - From Matlab Workspace - From Disk files etc. , Systems - Interconnection of Linear and non linear blocks www. Vidyarthiplus. com Sinks - Displays - Scopes - To Matlab Workspace - To disk files etc. ,

Typical Simulink Model www. Vidyarthiplus. com

Launching Simulink Click Simulink icon Type simulink in Matlab command window www. Vidyarthiplus. com

Launching Simulink Click New Model Icon www. Vidyarthiplus. com

Launching Simulink www. Vidyarthiplus. com

Simulink Library Browser (Tool Boxes) www. Vidyarthiplus. com

Simulink Library Browser (Tool Boxes) - Aerospace - Data Acquisition - Communications - Simpowersystems - simechanics - Instrument Control - Fuzzy logic - Neural Network - RF Block set - Video and Image processing - Signal Processing - State flow - Target for Infineon XC 166 - Target for XPC 555 www. Vidyarthiplus. com

Commonly used Blocks www. Vidyarthiplus. com

Data Types in Simulink defines a Boolean (1 or 0) type, instances of which are represented internally by uint 8 values Typecasting Signals - Simulink displays an error whenever it detects that a signal is connected to a block that does not accept the signal's data type. - Explicitly typecast (convert) the signal to a type that the block does accept. - Use the Data Type Conversion block to perform such conversions www. Vidyarthiplus. com

Commonly Used Blocks Bus Creator (Many to One) - Used to bundle signal lines into bus signal - Number of signal lines to be bundled can be specified - Gives neat appearance in block diagram or model creation - To be used in conjunction with Bus selector block - The signals are ordered from top to bottom - The order of signals can be changed or shuffled in any sequence - The signal name can be specified for user clarity www. Vidyarthiplus. com

Commonly used blocks Bus Selector (One to Many ) - Used to select signal from a bundled signals (Bus creator) - The signals can be selected in the input sides - Data types supported as similar to bus creator - The order of signals can be changed or shuffled in any sequence - The signal name can be specified for user clarity www. Vidyarthiplus. com

Commonly used blocks The Logical Operator block performs the specified logical operation on its inputs. Select the Boolean operation connecting the inputs with the Operator parameter list. Rectangular gives rectangle shape box. Distinctive shape for the selected operator. The Scope block displays its input with respect to simulation time. The Demux block extracts the components of an input signal and outputs the components as separate signals. The output signals are ordered from top to bottom output port. The Sum block performs addition or subtraction on its inputs. This block can add or subtract scalar, vector, or matrix inputs The Terminator block can be used to cap blocks whose output ports are not connected to other blocks. When we run a simulation with blocks having unconnected output ports, Simulink issues warning messages. Using Terminator blocks to cap those blocks avoids warning messages. www. Vidyarthiplus. com

Commonly used blocks Specify the constant value output by the block. We can enter any MATLAB expression in this field, including the Boolean keywords, true or false. Out port blocks are the links from a system to a destination outside the system. The Product block performs multiplication or division of its inputs. The Relational Operator block performs the specified comparison of its two inputs. www. Vidyarthiplus. com

Commonly used blocks The Saturation block imposes upper and lower bounds on a signal. The Mux block combines its inputs into a single vector output. An input can be a scalar or vector signal. All inputs should be of the same data type and numeric type. The Data Type Conversion block converts an input signal of any Simulink data type to the data type and scaling specified by the block's Output data type parameter. Inport blocks are the links from outside a system into the system. The Repeating Sequence block outputs a periodic scalar signal having a waveform that you specify. You can specify any waveform, using the block dialog's Time values and Output values parameters. The Signal Generator block can produce one of four different waveforms: sine wave, square wave, sawtooth wave, and random wave. The signal parameters can be expressed in Hertz (the default) or radians per second. The Sine Wave block provides a sinusoid. The block can operate in either time-based or samplebased mode. www. Vidyarthiplus. com

Commonly used blocks The Relay block allows its output to switch between two specified values. When the relay is on, it remains on until the input drops below the value of the Switch off point parameter. vice-versa. The From block accepts a signal from a corresponding Goto block, then passes it as output. The data type of the output is the same as that of the input from the Goto block. From and Goto blocks allow you to pass a signal from one block to another without actually connecting them. The Display block shows the value of its input on its icon. The block has two scalar inputs. The block plots data in the first input (the x direction) against data in the second input (the y direction). The Pulse Generator block generates square wave pulses at regular intervals. The block's waveform parameters, Amplitude, Pulse Width, Period, and Phase Delay, determine the shape of the output waveform. www. Vidyarthiplus. com

Commonly used blocks sim power systems www. Vidyarthiplus. com

Commonly used blocks sim power systems www. Vidyarthiplus. com

Commonly used blocks sim power systems www. Vidyarthiplus. com

Simulink Exercises • Half wave diode rectifier (half_wave_diode. mdl) • Full wave bridge rectifier (full_wave_diode. mdl) • Simple PWM Generation (simple_pwm. mdl) • Half controlled bridge rectifier-Symmetric (Half_cont_bridge_rectifier_symmetric) • Half controlled bridge rectifier – Asymmetric(Half_cont_bridge_rectifier_asymmetric) • Fully controlled bride rectifier with RL Load (Full_cont_bridge. mdl) • Modeling of Battery connected DC Machine (Battery_DC_Machine. mdl) • TRIAC – Based fully controlled bridge rectifier(Triac_Fully_Cont_Bridge_Rect. mdl) • Single Phase Full Bridge Inverter (single_phase_bridge_inverter. mdl) • SPWM Single Phase Full Bridge – Bipolar Switching(SPWM_single_inv_bipolar. mdl) • SPWM Single Phase Full Bridge – Unipolar Switching(SPWM_single_inv_Unipolar) www. Vidyarthiplus. com

Half wave diode rectifier www. Vidyarthiplus. com

Half wave diode rectifier www. Vidyarthiplus. com

Full wave bridge rectifier www. Vidyarthiplus. com

Full wave bridge rectifier www. Vidyarthiplus. com

Simple PWM Generation www. Vidyarthiplus. com

Simple PWM Generation www. Vidyarthiplus. com

Half controlled bride rectifier - Symmetric www. Vidyarthiplus. com

Half controlled bride rectifier - Symmetric www. Vidyarthiplus. com

Half controlled bridge rectifier - Asymmetric www. Vidyarthiplus. com

Half controlled bridge rectifier - Asymmetric www. Vidyarthiplus. com

Fully controlled bridge rectifier www. Vidyarthiplus. com

Fully controlled bridge rectifier www. Vidyarthiplus. com

Battery connected DC machine www. Vidyarthiplus. com

Battery connected DC machine www. Vidyarthiplus. com

Triac Based Fully Controlled Bridge rectifier www. Vidyarthiplus. com

Triac Based Fully Controlled Bridge rectifier R-Load = 10 Ω / ᾳ = 30⁰ www. Vidyarthiplus. com

Triac Based Fully Controlled Bridge rectifier RL-Load R = 10 Ω, L =25 m. H / ᾳ = 30⁰ www. Vidyarthiplus. com

Triac Based Fully Controlled Bridge rectifier RC-Load R = 10 Ω, C =100 m. F / ᾳ = 30⁰ www. Vidyarthiplus. com

Triac Based Fully Controlled Bridge rectifier RC-Load R = 10 Ω, C =1 u. F / ᾳ = 30⁰ www. Vidyarthiplus. com

Single Phase Bridge Inverter www. Vidyarthiplus. com

Single Phase Bridge Inverter www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Bipolar Switching www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Bipolar Switching www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Bipolar Switching THD Measurement Select Continuous gui block Select FFT analysis www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Bipolar Switching THD Measurement www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Bipolar Switching THD Measurement www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Bipolar Switching THD Measurement www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Unipolar Switching www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Unipolar Switching www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Unipolar Switching www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Unipolar Switching www. Vidyarthiplus. com

SPWM Single Phase Full Bridge – Unipolar Switching www. Vidyarthiplus. com

Thank You www. Vidyarthiplus. com

- Slides: 106