0% found this document useful (0 votes)
56 views23 pages

Matlab Basics Tutorial: Electrical and Electronic Engineering & Electrical and Communication Engineering Students

This document provides a tutorial on basic Matlab concepts including polynomials, matrices, stability analysis, root locus analysis, and basic Simulink modeling. It covers representing polynomials as vectors in Matlab, matrix manipulation functions like transpose and inverse, analyzing system stability using characteristic equations and root locations, plotting root loci of transfer functions, modeling systems in Simulink using blocks and signals, and simulating a simple system with a sine wave input and gain block. The tutorial is intended for electrical and electronic engineering students to learn basic Matlab and Simulink skills.

Uploaded by

sushantnirwan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
56 views23 pages

Matlab Basics Tutorial: Electrical and Electronic Engineering & Electrical and Communication Engineering Students

This document provides a tutorial on basic Matlab concepts including polynomials, matrices, stability analysis, root locus analysis, and basic Simulink modeling. It covers representing polynomials as vectors in Matlab, matrix manipulation functions like transpose and inverse, analyzing system stability using characteristic equations and root locations, plotting root loci of transfer functions, modeling systems in Simulink using blocks and signals, and simulating a simple system with a sine wave input and gain block. The tutorial is intended for electrical and electronic engineering students to learn basic Matlab and Simulink skills.

Uploaded by

sushantnirwan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

Matlab Basics Tutorial

for
Electrical and Electronic Engineering & Electrical and Communication Engineering Students

Prepared by P.Leung Revised by I.Jahmeerbacus May 2004

P.L

Matlab Tutorial
1.0 Polynomials
In Matlab, a polynomial is represented by a vector. To create a polynomial in Matlab, simply enter each coefficient of the polynomial into the vector in descending order. For instance, let's say you have the following polynomial:

To enter this into Matlab, just enter it as a vector in the following manner
x = [1 3 -15 -2 9] x = 1 3 -15 -2 9

Matlab can interpret a vector of length n+1 as an nth order polynomial. Thus, if your polynomial is missing any coefficients, you must enter zeros in the appropriate place in the vector. For example,

would be represented in Matlab as:


y = [1 0 0 0 1]

2.0 Matrices
In matrix, each row of elements is separated by a semicolon (;) or a return:
B = [1 2 3 4;5 6 7 8;9 10 11 12] B = 1 5 9 2 6 10 3 7 11 4 8 12

B = [ 1 2 3 4 5 6 7 8 9 10 11 12] B = 1 5 9 2 6 10 3 7 11 4 8 12

P.L

Matrices in Matlab can be manipulated in many ways. For one, you can find the transpose of a matrix using the apostrophe key:
C = B' C = 1 2 3 4 5 6 7 8 9 10 11 12

It should be noted that if C had been complex, the apostrophe would have actually given the complex conjugate transpose. To get the transpose, use .' (the two commands are the same if the matix is not complex). Now you can multiply the two matrices B and C together. Remember that order matters when multiplying matrices.
D = B * C D = 30 70 110 D = C * B D = 107 122 137 152 122 140 158 176 137 158 179 200 152 176 200 224 70 174 278 110 278 446

Another option for matrix manipulation is that you can multiply the corresponding elements of two matrices using the .* operator (the matrices must be the same size to do this).
E = [1 2;3 4] F = [2 3;4 5] G = E .* F

E = 1 3 F = 2 4 G = 2 12 6 20 3 5 2 4

P.L

If you have a square matrix, like E, you can also multiply it by itself as many times as you like by raising it to a given power.
E^3 ans = 37 81

54 118

If wanted to cube each element in the matrix, just use the element-by-element cubing.
E.^3 ans = 1 27 8 64

You can also find the inverse of a matrix:


X = inv(E) X = -2.0000 1.5000 1.0000 -0.5000

or its eigenvalues:
eig(E) ans = -0.3723 5.3723

There is even a function to find the coefficients of the characteristic polynomial of a matrix. The "poly" function creates a vector that includes the coefficients of the characteristic polynomial.
p = poly(E) p = 1.0000 -5.0000 -2.0000

Remember that the eigenvalues of a matrix are the same as the roots of its characteristic polynomial:
roots(p)

ans = 5.3723 -0.3723

P.L

3.0 Stability of a system


A system is stable if all the roots of its characteristic equation lie on the left half of the splane otherwise the system is unstable. Given the characteristic equation is given by =0 determine the stability of the system. cl=[1 3 -15 -2 9]; r = roots(c1) r= -5.5745 2.5836 -0.7951 0.7860 The system is unstable.

Exercises :

1.

Form with Matlab the matrices 1 2 A= 3 4 2 4 B= 6 8 7 2 8 C= 1 5 3

Compute the following matrix computations: AB, BA, A+B, A+C, BC, CC, CCT 2. Given a matrix m1 and a vector v1:

Calculate the product m2=m1T v1:

P.L

3.

Write the following system of equations in matrix form (AX=B)

x + 4 y + 3z = 1 2x + z = 3 x y 2 z = 5
and then, by finding the inverse of the matrix A, solve to find X = ( x,y,z)T and hence x,y,z. 4. Consider the matrix 2 1 A= 4 1 (a) Find the eigen values of A (b) Determine the eigenvectors of A (c ) Create a 2X2 modal matrix M out of the column eigenvectors. Then evaluate M-1 and finally evaluate D = M-1AM. 5. Determine the stability of the system, given the characteristic equation is 1+ Kc /( 1 2 3)( 4 s + 1) = 0 4 s[ s + (1 / 1)][s + (1 / 2)][s + (1 / 3)]

use 1 =1, 2 = , 3 =1/3, Kc = 5 and 4 = 0.25.

P.L

4.0 Root Locus


Consider a simple RC circuit as shown in Fig. 1 in which a voltage source v(t) is applied to a series combination of a resistance R and capacitance C where e(t) is the voltage across the capacitor. In this example the system is the RC circuit, the system input is the voltage v(t) and the system output is the voltage e(t). The relation between the input and output of the system in the frequency domain is the transfer function.

Fig. 1 RC circuit Applying Kirchoffs law, v(t) = Ri(t) + e(t) = 1 idt C

1 idt C (1)

v(t) = Ri(t) + e(t)

Taking Laplace Transform of Eq. (1) and rearranging,the transfer function gives E(s) 1 = V(s) s + 1 where the time constant = RC

P.L

4.1 Plotting the root locus of a transfer function


From the example above, let = 1 then E(s) 1 = V(s) s + 1 To model this system into Matlab, create a new m-file and add the following code: G(s) = num=1; den=[1 1]; g=tf(num,den); rlocus(h)

Consider a system which has a transfer function: s+7 s(s + 5)(s + 15)(s + 20) the command to plot the root locus is given below: num=[1 7]; den=conv([1 0],[1 5]),conv([1 15],[1 20]); rlocus(num,den)

P.L

Exercises
1. Using Matlab, obtain the root locus of the transfer function of a system below: s 3 + 0.196s 2 + 2s s 4 + 0.392s 3 + 3.004s 2 + 0.588s 2. The open-loop transfer function for DC motors speed is derived by the expression: Q K = v (Js + b)(Ls + R) + K 2 where electrical resistance (R ) = 1 ohm electrical inductance (L)= 0.5H electromotive force constant (K)=0.01Nm/Amp moment of inertia of the rotor (J)=0.01 kgm2/s2 damping ratio of the mechanical system (b) = 0.1Nms input (v) : source voltage output (Q) : Rotating speed Create an m-file and obtain the root locus of the system.

P.L

4.2 Closed-loop response


In order to find the step response of a system, you need to know the closed-loop transfer function. You could compute this using the rules of block diagrams, or let Matlab do it for you:
[numCL, denCL] =

cloop(num, den)

The two arguments to the function cloop are the numerator and denominator of the openloop system. Unity feedback is assumed. The step response of your closed-loop system:
step(numCL,denCL)

Exercise 1
Find the closed loop response of the system given by the transfer function

5.0 Simulink Basics


Simulink is a graphical extension to MATLAB for the modeling and simulation of
systems. In Simulink, systems are drawn on screen as block diagrams. Many elements of block diagrams are available (such as transfer functions, summing junctions, etc.), as well as virtual input devices (such as function generators) and output devices (such as oscilloscopes).

5.1 Starting Simulink


Simulink is started from the MATLAB command prompt by entering the following command:
simulink

Alternatively, you can click on the "Simulink Library Browser" button at the top of the MATLAB command window as shown below:

P.L

The Simulink Library Browser window should now appear on the screen. Most of the blocks needed for modeling basic systems can be found in the subfolders of the main "Simulink" folder (opened by clicking on the "+" in front of "Simulink"). Once the "Simulink" folder has been opened, the Library Browser window should look like:

P.L

5.2 Basic Elements


There are two major classes of elements in Simulink: blocks and lines. Blocks are used to generate, modify, combine, output, and display signals. Lines are used to transfer signals from one block to another.

Blocks
The subfolders underneath the "Simulink" folder indicate the general classes of blocks available for us to use:

Continuous: Linear, continuous-time system elements (integrators, transfer functions, state-space models, etc.) Discrete: Linear, discrete-time system elements (integrators, transfer functions, state-space models, etc.) Functions & Tables: User-defined functions and tables for interpolating function values Math: Mathematical operators (sum, gain, dot product, etc.) Nonlinear: Nonlinear operators (coulomb/viscous friction, switches, relays, etc.) Signals & Systems: Blocks for controlling/monitoring signal(s) and for creating subsystems Sinks: Used to output or display signals (displays, scopes, graphs, etc.) Sources: Used to generate various signals (step, ramp, sinusoidal, etc.)

Blocks have zero to several input terminals and zero to several output terminals. Unused input terminals are indicated by a small open triangle. Unused output terminals are indicated by a small triangular point. The block shown below has an unused input terminal on the left and an unused output terminal on the right.

Lines
Lines transmit signals in the direction indicated by the arrow. Lines must always transmit signals from the output terminal of one block to the input terminal of another block. One exception to this is that a line can tap off of another line. This sends the original signal to each of two (or more) destination blocks, as shown below:

P.L

5.3 Building a System


To demonstrate how a system is represented using Simulink, we will build the block diagram for a simple model consisting of a sinusoidal input multiplied by a constant gain, which is shown below:

This model will consist of three blocks: Sine Wave, Gain, and Scope. The Sine Wave is a Source Block from which a sinusoidal input signal originates. This signal is transferred through a line in the direction indicated by the arrow to the Gain Math Block. The Gain block modifies its input signal (multiplies it by a constant value) and outputs a new signal through a line to the Scope block. The Scope is a Sink Block used to display a signal (much like an oscilloscope). We begin building our system by bringing up a new model window in which to create the block diagram. This is done by clicking on the "New Model" button in the toolbar of the Simulink Library Browser (looks like a blank page). Building the system model is then accomplished through a series of steps: 1. The necessary blocks are gathered from the Library Browser and placed in the model window. 2. The parameters of the blocks are then modified to correspond with the system we are modelling. 3. Finally, the blocks are connected with lines to complete the model.

P.L

The same method can be used to place the Gain and Scope blocks in the model window. The "Gain" block can be found in the "Math" subfolder and the "Scope" block is located in the "Sink" subfolder. Arrange the three blocks in the workspace (done by selecting and dragging an individual block to a new location) so that they look similar to the following:

5.4 Modifying the Blocks


Simulink allows us to modify the blocks in our model so that they accurately reflect the characteristics of the system we are analyzing. For example, we can modify the Sine Wave block by double-clicking on it. Doing so will cause the following window to appear:

This window allows us to adjust the amplitude, frequency, and phase shift of the sinusoidal input. The "Sample time" value indicates the time interval between successive

P.L

readings of the signal. Setting this value to 0 indicates the signal is sampled continuously. Let us assume that our system's sinusoidal input has:

Amplitude = 2 Frequency = pi Phase = pi/2

For our system, we will let k = 5. Enter this value in the "Gain" field, and click "OK" to close the window.The Scope block simply plots its input signal as a function of time, and thus there are no system parameters that we can change for it. We will look at the Scope block in more detail after we have run our simulation.

5.5 Running Simulations


Now that our model has been constructed, we are ready to simulate the system. To do this, go to the Simulation menu and click on Start, or just click on the "Start/Pause Simulation" button in the model window toolbar

P.L

Note that the output of our system appears as a cosine curve with a period of 2 seconds and amplitude equal to 10. Does this result agree with the system parameters we set? A

5.6 Example: Free Body Diagram and System Equation


To demonstrate how Simulink can be used to investigate a real-world system, we will look at a simplified, first-order model of the motion of a car. If we assume the car to be travelling on a flat road, then the horizontal forces on the car can be represented by:

In this diagram:

v is the horizontal velocity of the car (units of m/s). F is the force created by the car's engine to propel it forward (units of N). b is the damping coefficient for the car, which is dependent on wind resistance, wheel friction, etc. (units of N*s/m) We have assumed the damping force to be proportional to the car's velocity.

P.L

M is the mass of the car (units of kg).

Writing Newton's Second Law for the horizontal direction thus gives:

For our system, we will assume that: M = 1000 kg b = 40 N*sec/m

Building System Model


This system will be modeled in Simulink by using the system equation derived above. This equation indicates that the car's acceleration (dv/dt) is equal to the sum of the forces acting on the car (F-bv) divided by the car's mass:

To model this equation, we begin by inserting a Sum block and a Gain block into a new model window. The Sum block represents adding together the forces and the Gain block symbolizes dividing by the mass. Next, we modify these blocks to properly represent our system. The Sum block needs to add the motor force (F) and subtract the damping force (bv). We also modify the Gain block so that it divides by the car's mass. Double-click on the block and change the Gain to 1/1000 (dividing by 1000 is the same as multiplying by 1/1000). Draw lines to the open input terminals of the Sum block and open output terminal of the Gain block and label the signals and blocks in the model.

To relate the car's acceleration (v_dot in the Simulink model) to its velocity-dependent damping force, we will integrate the v_dot signal. Place an Integrator block (from the Continuous subfolder) in the model (you do not need to change its parameters), and draw and label the velocity signal so that the model looks like:

P.L

To obtain the damping force from the velocity, we need to branch the velocity signal and multiply it by the damping coefficient (b). Block (the Gain block must be selected in the model window when this is done). Finally, edit the Gain block's parameters so that its gain equals the damping coefficient of the system (40 N*sec/m). These additions to the model should cause it to look like:

Note that the block diagram is now set up with input F (engine force) and output v (car velocity).

System Response to Step Input


To be able to successfully simulate the system, we need to specify an applied input, F. Let us assume the car is initially at rest, and that the engine applies a step input of F = 400 N at t = 0. Insert a Step block from the Sources subfolder into the model, and also

P.L

add a Scope block from the Sinks subfolder to monitor the system's velocity, v. The Simulink model window should now look like:

The Step block must be modified to correctly represent our system. Double-click on it, and change the Step Time to 0 and the Final Value to 400. The Initial Value can be left as 0, since the F step input starts from 0 at t = 0. The Sample Time should remain 0 so that the Step block's input is monitored continuously during simulation. Next, run a simulation of the system (by clicking the "Start/Pause Simulation" button or selecting Simulation, Start). Once the simulation has finished, double-click on the Scope block to view the velocity response to the step input.

Note that this graph does not appear to show the velocity approaching a steady-state value, as we would expect for the first-order response to a step input. This result is due to the settling time of the system being greater than the 10 seconds the simulation was run.

P.L

To observe the system reaching steady-state, change the Stop Time to 150 seconds. Now, re-run the simulation and note the difference in the velocity graph:

From this graph, we observe that the system has a steady-state velocity of about 10 m/s (about 22 mph), and a time constant of about 25 seconds. Let's check these results with our original equation. For a step input of F = 400 N, the system equation is:

Setting dv/dt = 0 gives a steady-state velocity of 10 m/s, a result which agrees with the velocity graph above. Next, we find the time constant of the system using the characteristic equation, which is:

Solving this gives the characteristic root, s = -0.04, and thus the time constant is indeed 25 seconds (tau = -1/s), as we predicted using the graph.

P.L

Exercises
1. Consider the response of the system if a pulse, instead of a step, input is applied. This
is approximately equivalent to the car's driver pressing and holding the gas pedal in a constant position for a specified period of time, and then releasing the pedal. To model a pulse input using Simulink, insert another Step block(step1) and a Sum block in the system . The parameters for the original "Step" block can be left as they were before. Modify the "Step1" block parameters to the following: Step Time = 100 Initial Value = 0 Final Value = -400 These settings enable the "Step1" block to cancel out the input from the "Step" block starting at t = 100. To monitor the input of the system, F, we insert another scope into the model window , Modify the simulation time to 200 seconds, then run the simulation. : 2. Analyse the response of the system below to a unit step change when operating in closed loop.

a Select a unit step change from 0 to 1 to occur at time = 5. b Use the Transfer Fcn block to the workspace window. Double click on this block and enter the numerator and denominator coefficients which represent the system defined above, i.e. the numerator should be equal to [600] and the denominator should be [1 14 59 70]. The coefficients are entered in descending powers of s.

P.L

3. Use Simulink to model an equation. Let's consider...


,

where the displacement x is a function of time t, frequency w, phase angle phi, and amplitue A. In this example the values for these parameters are set as follows: frequency=5 rad/sec;phase=pi/2;A=2. t=(0:.01:10) 4. 4. Refer to the RC circuit of Fig 1 in Root Locus tutorial, the transfer function of the system is given by E(s) 1 = V(s) s + 1 Simulate the circuit in a closed loop system with the following parameters: Step input =5 Stimulating time =2s (i) R=1ohm, C = 1uF (ii) R=2ohms, C= 1uF

P.L

5.7 AC circuit simulation using Simulink


A series R-L circuit with R = 5 and L = 25mH is connected to a 230V (rms), 50 Hz single phase

supply. It is required to simulate the circuit to obtain the supply and inductor voltage waveforms (vs(t) and vL(t)), as well as the load current, i(t). Applying KVL to the circuit, the instantaneous supply voltage and current can be expressed as:

v s (t ) = i (t ) R + L

di (t ) dt

(1)

Equation (1) can be expressed in integral form as:

i (t ) =

1 (v s (t ) i(t ) R )dt L

(2)

The inductor voltage can be found using Equation (1):

v L (t ) = v s (t ) i (t ) R
Exercise:

(3)

1. Implement Equations (2) and (3) in Simulink using the following blocks: 2. Sine Wave, Gain, Integrator, Sum, Clock, Mux, Scope, To Workspace. 3. Set the initial condition of the integrator to zero. 4. Set the simulation time to 0.5 secs and run the simulation. 5. Run the simulation and produce plots of I(t), vs(t) and vL(t) 6. Comment on the results by comparing the amplitudes and phase differences with theory.

7. Compare the rms values of the currents and voltages obtained from the simulation with those calculated from theory. 8. Determine the power factor of the circuit using simulation results and calculations. Comment on any discrepancies.
I. Jahmeerbacus 19.5.04

P.L

You might also like