benc 2113 denc 2532 ecadd - razorjr.files.wordpress.com · fakulti kejuruteraan elektronik dan...

13
1 FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER DENC 2532 ECADD LAB SESSION 6/7 MATLAB FUNDAMENTAL AND SIMULINK TOOLBOX Prepared by: Hamzah Asyrani Sulaiman Computer Engineering Department, FKEKK (Sept. 2013)

Upload: others

Post on 18-Jan-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

1

____________________________________________ UNIVERSITI TEKNIKAL MALAYSIA MELAKA

FAKULTI KEJURUTERAAN ELEKTRONIK DAN

KEJURUTERAAN KOMPUTER

BENC 2113

ECADD

LAB SESSION 5

PSPICE FOR DC ANALYSIS

Prepared by:

Norhashimah Mohd Saad

Computer Engineering Department, FKEKK

FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

DENC 2532

ECADD

LAB SESSION 6/7

MATLAB – FUNDAMENTAL AND SIMULINK TOOLBOX

Prepared by:

Hamzah Asyrani Sulaiman Computer Engineering Department, FKEKK

(Sept. 2013)

Page 2: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

2

LAB 6: MATLAB FUNDAMENTALS

1.0 OBJECTIVES

After completing this lab session, you should be able to:

Compute mathematical operations in Matlab.

Create M-file programs.

Plot graph and programming in Matlab.

Apply conditional statements and loops in programming.

2.0 INTRODUCTION

MATLAB stands for MATrix LABoratory. It was first developed at University of California

at Berkely. Now it is commercial software bearing the trademark of The MathWorks inc. and

is used widely in many engineering fields. Since its original development it has involved into

a comprehensive and sophisticated interactive system and programming language for general

scientific and technical computation. It is one of a variety of high level computational

mathematical tools that are widely used in teaching, research and education. For instance on

executing Matlab the user is presented with a window containing three panes:

Workspace/current directory pane, a command history pane and a Matlab command window

pane.

3.0 MATLAB IN MATHEMATICAL OPERATIONS

Calculator: To investigate the precedence of mathematical operations, try the following in a

Matlab command window:

>> 2 + 3

>> 2.0 + 3.0

>> 2 - 2.0

>> 2/3

>> 2/3.0

>> 2/6*3

>> 2*6/3

>> 1 + 2 - 3 * 4 / 5

>> 1 + (2 - 3) * (4/5)

>> 5^3

Built in functions: MATLAB has many predefined mathematical functions, such as square

roots, exponentials, logarithms, sines and cosines and their inverses, and absolute value. Try: >> pi

>> sin(pi)

>> cos(0)

>> tan(11)

>> atan(6)

>> sqrt(5^2)

>> log2(10)

>> log10(10)

>> exp(5)

Page 3: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

3

Variables: Variables are defined in Matlab by assigning a value to any arbitrary string of

characters. For example, to define a variable, type:

>> num_1 = 3

>> num_2 = 5

Basic Vectors: Type in the following, observe, learn, and try some variations of your own to

see if you can work out what is going on:

Define a length vector or 1x5 Matrix:

>> x=[1 2 3 4 5];

>> y=[2 2 2 2 2];

To view results: >> x

>> y

Transpose of a vector: >> x’

>> y’

Note: The resulting vector is still a 5 length vector but a 5x1 matrix.

Define a 3x3 Matrix: >> A=[ 2 1 0; 1 2 1; 0 1 2];

>> C=[ 4 0 0; 0 4 0; 0 0 4];

Note: A vector is nx1 or 1xn matrix. To view variable names: >> whos;

To view variable A and C: >> A

>> C

To clear variables, for example variable A: >> clear A;

The command means clear variable A.

Page 4: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

4

Element by Element Operations: Matlab support element-by-element operations such as

Array multiplications, addition and subtraction. Try the following array operations:

Sum of two matrices:

>> z=x+y

Difference of two matrices:

>> z=x-y

Multiplication of a scalar with a matrix:

>> a=2; % define variable a=2

>> z=a*x

Array multiplication:

>> A=x.*y

Inverse of a matrix:

>> B=A’

Inner product of two vectors:

>> z=x*y’

The result is the sum of products.

Product of two vectors:

>> C=A*B

Roots of a polynomial. Define polynomial as 122 xx . Display the roots of the

polynomial:

>> q=[1 2 1];

>> roots(q)

Note: the polynomial q is (x+1)(x+1).

Page 5: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

5

4.0 GRAPHICS ON MATLAB

MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as

annotating and printing these graphs. This section describes a few of the most important

graphics function and provides examples of some typical applications.

Creating a Plot

The plot function has different forms, depending on the argument. If y is a vector, plot(y)

produces a piecewise linear graph of the statements of y versus the index of the elements of y.

if you specify two vectors as arguments plot(x,y) produces a graph of y versus x. Now, try the

following to plot a linear equation, y=mx+c:

>> clear all; % clear all variables

>> x=[0 1 2 3 4 5]; % Define a 1x5 matrix

>> c=2; m=1; % define a constant c, and m

>> whos; % View all variables

>> y0=m*x+c; % Define a linear equation as y0=mx+c

The results for y0 versus x can be plotted using command plot:

>> figure; % create a new figure

>> plot(x,y0); % plot y0 versus x

Now label the axes and add a title to the plot:

>> title(‘plot of a linear equation’); %title of plot

>> ylabel(‘y-axis’); %label for the y-axis of the plot

>> xlabel(‘x-axis’); %label for the x-axis of the plot

>> grid on; % setting grid lines

For further information on plot command, type:

>> help plot;

Now, plot a data for a set of sequence y versus x by using STEM command. The stem

command will plot the data in discrete sequence. Try this:

>> x=[1:10]; % sequence x is from 1 to 10 in 1 increment

>> y1=[20 40 60 80 90 60 50 30 20 10]; % sequence y

>> figure; % create a new figure

>> stem(x,y1); % plot in a discrete sequence format

Label the axes and add a title to the plot:

>> title(‘stem plot y1 versus x’); %title of plot >> ylabel(‘y-axis’); %label for the y-axis of the plot

>> xlabel(‘x-axis’); %label for the x-axis of the plot

>> grid on; % setting grid lines

Page 6: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

6

Multiple Data Set in 1 Graph

Multiple x-y pair arguments create multiple graphs with single call to plot. MATLAB

automatically cycles through a predefined list of colors to allow discrimination between each

set of data. For example, these statements plot three related function of x, each curve in a

separate distinguishing color.

>>x = 0:pi/100:2*pi;

>>y1 = sin(x);

>>y2 = sin(x-0.25);

>>y3 = sin(x-0.5);

>>plot(x,y1,x,y2,x,y3);

The legend command provides an easy way to identify the individual plots.

>>legend(’sin(x)’,’sin(x-0.25)’,’sin(x-0.5)’);

Label the title and axis of the plot:

>> title(‘plot of sine functions’);

>> ylabel(‘y-axis’); xlabel(‘x-axis’);

>> grid on;

The hold command enables you to add plots to an existing graph. When you type hold on

MATLAB does not replace the existing graph when you issue another plotting command; it

adds the new data to the current graph, rescaling the axes if necessary.

Multiple Plot in 1 Figure

The subplot command enables you to display multiple plots in same windows or print

them on same piece of paper.

Typing subplot(m,n,p) partitions the figure window into an m by n matrix of small

subplot and selects the path subplot for the current plot. The plots are numbered along first

the top row of the figure window, then the second row, and so on.

For this example, the statements plot data in four different subregions of the figure

window by using subplot command.

>> t = 0:pi/10:2*pi;

>> [x,y,z] = cylinder(4*cos(t));

>> subplot(2,2,1);

>> mesh(x);

>> subplot(2,2,2);

>> mesh(y);

>> subplot(2,2,3);

>> mesh(z);

>> subplot(2,2,4);

>> mesh(x,y,z);

>> grid on;

Note that MESH command plots the coloured parametric mesh defined by four matrix

arguments in three dimensional plots. You can use the help function to understand the

command.

5.0 PROGRAMMING IN MATLAB

Page 7: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

7

Flow Control

if statements

The if statements evaluates a logical expression and executes a group of

statements when the expression is true. The optional elseif and else

keywords provide for the execution of alternate groups of statements. An

end keyword, which matches the if, terminates the last group of

statements. The groups of statements are delineated by four keywords.

A = input ('Enter the value of A: ')

B = input ('Enter the value of B: ')

if A > B

‘greater’

elseif A < B

‘less’

elseif A == B

‘equal’

else

‘unknown error’

end

for statements

The for loop repeats a group of statements a fixed, predetermined number

of times. A matching end delineates the statements.

m = 0;

for n = 3:32

m = m + n;

end

m

while statements

The while loop repeats a group of statements an indefinite number of

times under control of a logical condition. A matching end delineated the

statements.

a = 0;

b = 10;

while b > a

b = b - 1;

end

a

b

To observe flow control command such as IF, FOR , WHILE, type the follower:

>>help if

>>help for

>>help whil

6.0 Matlab Scripting File (M-file)

Page 8: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

8

MATLAB statements can be prepared with any editor, and stored in a file for later use.

Such a file is referred to as a script or an “M-file (since they must have a name extension of

the form filename.m). Writing M-files will enhance your problem solving productivity since

many MATLAB commands can be run from one file without having to enter each command

one-by-one at the MATLAB prompt. This way, corrections and changes can be made in the

M-file and re-run easily.

Suppose that we create a program file myfile.m in the MATLAB language. The

commands in this file can be executed by simply giving the command >> myfile from MATLAB prompt.

The MATLAB statements will run like any other MATLAB function. You do not need to

compile the program since MATLAB is an interpretative (not compiled) language. An M-file

can reference other M-files, including referencing itself recursively.

Using the MATLAB Script Editor (click FileNewM-file), create the following file,

named sketch.m:

[x y] = meshgrid(-3:.1:3, -3:.1:3);

z = x.^2 - y.^2;

mesh(x,y,z);

Save the file as sketch, then start MATLAB from the current directory containing

this file, and enter the name of the file at command window, then the result will be displayed:

>> sketch

The result is the same as if you had entered the three lines of the file, at the prompt.

Try it to see the results.

7.0 TASK: PROGRAMMING EXAMPLES USING MATLAB

EXAMPLE 1: Program to Add Two Numbers

Type all the command inside M-file. Save file as ‘add’. This program is to add two

numbers:

% Function to add two numbers

function[z]=add(a,b)

z=a+b;

fprintf('the total value is = %f\n', z);

To run M-file, just type in at the Matlab prompt (command window) the name of the

file. Your file is calling ‘add’.

>> add(5,6);

the total value is = 11.000000

EXAMPLE 2: Computing Polar Coordinates

Given the (x,y) coordinates of a point, compute its polar coordinates, (r,) of that

point, where:

Page 9: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

9

x

yyxr 1-22 tan

Solution (the steps):

1. Enter the input of coordinates x and y.

2. Compute r =sqrt(x^2+y^2).

3. Compute the angle, theta :

a. if 0x theta = atan(y/x)

b. else theta = atan(y/x)+pi

c. end

4. Convert angle to degrees. theta = theta*(180/pi)

5. Display the result r and theta

Type all the command inside M-file. Save file as ‘polar’. This program is to compute

polar coordinate:

The program is:

% coordinate_polar

x = input ('Enter the value of x: '); y = input ('Enter the value of y: ');

r = sqrt(x^2+y^2);

if (x>=0)

theta = atan(y/x);

else

theta = atan(y/x)+pi end

theta = theta*(180/pi) ;

fprintf('the hypoteneus is = %f\n', r); fprintf('the theta is = %f\n', theta);

To run M-file, just type in at the Matlab prompt (command window) the name of the

file. Your file is calling ‘polar’.

>> polar

Enter the value of x: 4

Enter the value of y: 5

the hypoteneus is = 6.403124

the theta is = 51.340192

Page 10: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

10

LAB 7: MATLAB SIMULINK

1.0 OBJECTIVES

After completing this lab session, you should be able to:

• Building the model using Simulink.

• Design simulation diagrams using Simulink.

• Export results to Matlab Workspace.

2.0 INTRODUCTION

Simulink is built on top of Matlab, so you must have Matlab to use Simulink. Simulink

provides a graphical user interface that uses a various types of elements called blocks to

create a simulation of a dynamic system-that is a system that can be modeled with differential

or difference equations whose independent variable is time. For example, one block type is a

multiplier, another performs a sum, and another is an integrator. The Simulink graphical

interface enables you to position the blocks to describe complicated systems for simulation.

3.0 SIMULATION DIAGRAMS

You develop Simulink models by constructing a diagram that shows elements of the problem

to be solved. Such diagrams are called simulation diagrams or block diagrams.

Consider the equation:

𝑑𝑦

𝑑𝑡= 10𝑓(𝑡) (1)

Its solution can be represented symbolically as:

𝑦(𝑡) = ∫ 10𝑓(𝑡)𝑑𝑡 (2)

The block containing the integral sign f represents the integration process of the equation.

The integration symbol in equation (2) can be replaced by the operator symbol 1/s, which

derives from the notation used for Laplace Transform. Thus the equation (2) is represented

as:

𝑦 = 10𝑓 (1

𝑠) (3)

The simulation diagram for equation (3) is:

Figure 1: Simulation diagram for 𝑦 = 10𝑓 (1

𝑠)

f y1

s

Integrator

10

Gain

Page 11: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

11

Another element used in simulation diagrams is the summer that is used to subtract as well as

to sum variables. The summer symbol can be used to represent the equation:

𝑑𝑦

𝑑𝑡= 𝑓(𝑡) − 10𝑦 (4)

Equation (4) can be expressed as

𝑦(𝑡) = ∫[𝑓(𝑡) − 10𝑦]𝑑𝑡 (5)

Or as

𝑦 =1

𝑠(𝑓 − 10𝑦) (6)

The simulation diagram for the equation (6) is:

Figure 2: Simulation diagram for 𝑦 =1

𝑠(𝑓 − 10𝑦)

4.0

f y1

s

Integrator

10

Gain

Page 12: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

12

TASK 1: SIMULATION USING SIMULINK

Use Simulink to solve the following problem for 0 ≤ t ≤ 13.

𝑑𝑦

𝑑𝑡= 10 sin 𝑡 𝑦(0) = 0 (7)

The exact solution is 𝑦(𝑡) = 10(1 − cos 𝑡). To construct the simulation, do the following

steps:

Page 13: BENC 2113 DENC 2532 ECADD - razorjr.files.wordpress.com · FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER KEJURUTERAAN KOMPUTER BENC 2113 ECADD ECADD LAB SESSION 5 PSPICE

13

1. Start Simulink. You can click the icon on the Matlab toolbar or type simulink

from the command line.

2. Open a new model window, select New-s Model on the File menu of either the

Matlab desktop or the Simulink Library Browser toolbar. You can also click the D

button on the Library Browser toolbar.

3. Select and place in the new window the Sine Wave block from the Sources library.

Double click on it to open the Block Parameters window, and make sure the

Amplitude is set to 1, the frequency to 1, the phase to 0, and the sample time to O.

Then click OK.

4. Select and place the Gain block from the Math Operations library, double click on it,

and set the Gain Value to 10 in the Block Parameter window. Then click OK.

5. Note that, the value 10 then appears in the triangle. To make the number more visible,

click on the block, and drag one of the corners to expand the block so that all the text

is visible.

6. Select and place the integrator block from the continuous library, double click on it to

obtain the Block Parameters window, and set the initial condition to 0 (this is because

y(O)=O). Then click OK.

7. Select and place the Scope block from the Sinks library.

8. Once the blocks have been placed as shown in Figure 2, connect the input port on

each block to the output port on the preceding block. To do this, move the cursor to an

input port or an output port; the cursor will change to a cross. Hold the mouse button

down, and drag the cursor to a port on another block. When you release the mouse

button, Simulink will connect them with an arrow pointing at the input port. Your

model should now look like that shown in figure 2.

9. Click on the Simulation menu, and click the Configuration Parameters item.

10. Click on the Solver tab, and enter 13 for Stop time. Make sure the Start time is O.

Then click OK.·