Anda di halaman 1dari 47

LABORATORY Manual

For the course

COMPUTER SCIENCE AND


NUMERICAL ANALYSIS

Department of Chemical Engineering


M. N. S. University of Engineering & Technology,
Multan, Pakistan

LAB #
1

LIST OF EXPERIMENTS
Introduction to C++ (Header Files, Cout statement, getch () etc...)

Variable Declaration and its usage in Mathematical Equations/Operations

Introduction of Cin and If-Else Statements

Introduction of Loops

Introduction of MATLAB

Introduction to vectors in MATLAB

Matrix Calculations in MATLAB

MID TERM

8
9

Solution of Linear Equations and Eigen Values using MATALB

10

Plotting of Various types of Graphs using ezplot and plot Functions

11

Symbolic Differentiation and solution of Differential Equations

12

Transfer Function Manipulation and Study of Transient Response of 1st and 2nd
Order Systems

13

Plotting Bode Plot using MATLAB

14

Root Locus Diagrams Solution using MATALB

15

Introduction to Simulink

16

Simulation of a Typical Feedback Control Loop in Simulink

INTRODUCTION TO C++
OBJECTIVE:

To understand the basic of C++ Language and Header Files and their
Purpose in the Program.
EQUIPMENT AND SOFTWARE:
Personal Computer Loaded with C++ Compiler
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
C++, pronouced as see plus plus. It is powerfull computer programming
language. It is the advance version of C language. The C is a procedural language
while C++ is an object oriented programming language.
A procedural language is a computer programming language that follows, in
order, a set of commands. Examples of computer procedural languages
are BASIC, C, FORTRAN, and Pascal.
is
a
type
of programming in
which programmers define not only the data type of a data structure, but also the
types of operations (functions) that can be applied to the data structure. In this way,
the data structure becomes an object that includes both data and functions. In
addition, programmers can create relationships between one object and another.
For example, objects can inherit characteristics from other objects.
Object-oriented

programming

Structure of C++ Programs:


A C++ program consists of three main parts. These are:
1) Preprocessor Directives
2) The main () Function
3) C++ Statements
Preprocessor Directives:
The instructions that are given to the compiler before the beginning of the actual
program are called preprocessor direcctives. These are also known as compiler
directives.

These preprocessor directives normally start with a number sign (#) and the
keyword include or define. For example, preprocessor directives are used to
include HEADER FILES in the program.
Header file is the C++ source file that contains definitions of library functions
objects. For example iostream.h has definitions of different built-in input and
output objects and functions
The main () Function:
It indicates the begning of C++ program. This must be included in every program.
When C++ program is executed, the control goes directly to the main () function. If
main () function is not included, the program is not compiled and an error message
is generated.
The syntax of the main () function is:
Main ()
{
Program statements..
}
C++ Statements:
The statements of the program are written under the main () function between the
curly braces {}. These statements are the body of the program. Each statement in
C++ ends with semicolon (;).
C++ is a case sensitive language. The C++ statements are normally written in
lowercase letters but in some exceptional cases, these can also be writtten in
uppercase.

The First Program


# include<conio.h>
#include<stdio.h>

#include<iostream.h>
Void main () {
Cout <<This is my first Program;
Getche ();
}

Descriptions:
Conio.h header file used in c programming contains functions for console
input/output. Some of the most commonly used functions of conio.h are clrscr,
getch, getche, etc.
Iostream.h header file include cout function
Compiler starts compiling from the main funciton and onward and creates a
machine code which is called object code. It is stored in a new file with obj
extension. The objec code is then linked to libraries. After this .exe file is created.
This .exe file is then run from the operating system command line.
OUTPUT:
Output of the above program is
This is my first Program

Assignments:
i.
ii.
iii.
iv.
v.

Write above program again and remove conio.h header file and note down
the errors.
Write above program again and remove stdio.h header file and note down
the errors.
Write above program again and remove iostream.h header file and note
down the errors.
Write a program which display your name and class roll number on the
output screen.
Write a program which displays your name, class roll number and
department on the output screen using three cout statements.

vi.

Study about Escape Sequences...

VARIABLE DECLARATION AND


INITIALIZATION
OBJECTIVE:

To understand how variables declared and initialized in the program and


their use in the arithmetic operations.
EQUIPMENT AND SOFTWARE:
Personal Computer Loaded with C++ Compiler
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
A quantity whose value may change during execution of the program is called
variable. It is represented by a symbol or a name.
A variable represents a storage or memory location in the computer memory. Data
is stored into the memory location. The name of the memory location, i.e. the
variable name, reamins fixed during execution of the program but the data stored
in that location may change from time to time.
Some rules that must be follow to write the variable name
The first character of variable name must be an alphabetic character.
Underscore can be used as first character of variable name.
Blank spaces are not allowed in a variable name.
Special characters, such as arithmetic operations, #,^, cannot be used in a
variable name.
Reserved words cannot be used as a varible name.
A variable name declared for one data-type cannot be used to declare
another data-type.
The maximum length of a variable name depends upon the compiler of C++

There are following basic types of variable in C++


Type
Bool

Description
Stores either value true or false.

Char
Int
Float
Double

Typically a single octet (one byte). This is an integer type.


The most natural size of integer for the machine.
A single-precision floating point value.
A double-precision floating point value.

Declaration of variables:
Assigning the name and data type that a variable can hold is called declaration of
the variable
The syntax to declare a variable in C++ is:
Type list of variables;
Where
Type: specifies data type of variables. Like int, float, etc...
List of variables: specifies a list of variables separated by commas
Int ab, xyz, d, s;
Int a, xy;
Float b;
Char nm [15];
Double sum;

Initialization of variables:
Assigning a known value to a variable at the time of its declaration is called
intitializing of the variable.
Int a=10, b=50;
Sample program:
# include<iostream.h>
Void main (){

Int a=4, b=1997;


Float xy=3.4;
Cout<<a<<endl;
Cout<<b<<endl;
Cout<<xy<<endl;
Getche ();
}
OUTPUT OF THE ABOVE PROGRAM
4
1997
3.4
Arithmetic Operators:
The following arithmetic operators used in C++
Operator
+
*
/
%

description
addition
subtraction
multiplication
division
modulo

Assignments:
i.
ii.
iii.

Write a program to perform the arithmetic operations by using all arithmetic


operators. Also print the results on the screen.
Write a program to calculate the radius of circle (radius=r2)
Write a program in which values are assigning to two different variables.
Interchange these values using three variables and show the result on the
screen.

iv.
v.

Write a program to assign the numeric value to a variable year. Calculate the
number of months and print the result on the screen.
Write a program in which values are assigning to two different variables.
Interchange these values using two variables and show the result on the
screen.

Conditional Statements
OBJECTIVE:
To understand the Cin input stream and conditional statements (if-else)

EQUIPMENT AND SOFTWARE:


Personal Computer Loaded with C++ Compiler
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
Cin stands for console input. It is an input stream. It is used as input statement to
get input from the keyboard during execution of the program.The Cin object is
also a part of iostream header file
The syntax of Cin is:
Cin>> var1;
Where
Cin: represents the object name use as an input stream. This stream represents data
coming from input device keyboard.
>>: Extraction operator or get from operator. It gets an input from the input device
and assigns it to the variable.
Var1: normaly variable name.
Conditional Statements:
The statements which can change the order of the execution of the program are
called condtional statements. These statements also known as selection statements.

Relational Operators:
The operators that are used to specify a relation between two expression or values
are known as relational operators.
Following table summarizes the relational operators.

The if Statement:
The if statement is used to execute (or ignore) a set of statements after testing a
condition.
The if statement evaluate a condition. If the given condition is true, the statement
following the if statement is executed. If the given condition is false, the
statement following the if statement condition is ignored and control transfer to
the next statement.
The syntax of the if statement is:
If (condition)
Statement-1;
Statement-2;
Condition: specifies a condition or a relational expression.
The following program executes a single statement if the given condition is true.
# include <iostream.h>
Void main () {
Int A, B;

A=100;
B=50;
If (A>B)
Cout<<Islamabad<<endl;
Cout<<ok;
Getche ();
}
The if-else Statement:
This is another form of the if statement. It is used for making two-way decisions.
In this statement, one condition and two blocks of statements are given. Either one
of the two blocks of statements is executed after evaluating the condition.
The syntax of if-else statement is:
If (condition)
Statement-1;
Else
Statement-2;
Assignments:
i.

ii.
iii.
iv.
v.

Write a program to input a number. If the number is divisible by 3 then print


the message on the screen that the number is divisible by three. Use if
statement.
Write a program to input two integer values and find out whether the first or
second number is greater.
Write a program to calculte the electriciy bill.
Write a program to input a number from the keyboard. Use if-else statement
to find out whether the number is less than or greater than 100.
Write a program to input three integers and find maximum from these
integers.

vi.
vii.

Write a program to input three integers and find minimum from these
integers.
Write a program which tells that number is Even or Odd.

Loops Statements
OBJECTIVE:

To understand how loop works in C++ programming and what are


advantages of these
EQUIPMENT AND SOFTWARE:
Personal Computer Loaded with C++ Compiler
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
In our daily life, most of the things are repeated, so repetition is very useful
structure in the programming. Lets discuss a problem to understand it thoroughly.
We have to calculate the sum of first 10 integers. Following statement may be one
way to do it.
Cout<<Sum of first 10 integers is :<< 1+2+3+4+5+6+7+8+9+10;
This method is perfectly fine as the syntax is right. The answer is also correct. This
procedure can also b adopted while calculating the numbers from 1 to 100. We can
write the above statement adding all the numbers from 1 to 100. But this method
will not be suitable for computing the sum of numbers from 1 to 1000. The
addition of a very big number of integers will result in a very ugly and boring
statement. Lets analyze it carefully. Out first integer Is 1, is there ant other way to
find out what is the next integer. Yes, we can add 1 to the integer and get the next
number which is 2. To find the next integer we add 1 to the previous integer.
We have to calculate the sum of first 1000 integers by taking a variable sum of
type int and assign a value of 0 to it. Now we get the first integer 1. We add the
sum to this. Now we get the next integer which can b obtained by adding 1 to the
previous integer i.e. 2 and add it to the sum. And get the next integer adding 1 to
the previous integer i.e. 3 and so on.
The For loop:

The for loop is designed to iterate a number of times. Its syntax is:
for (initialization; condition; increase){
Statement;}
This loop repeats statement while condition is true. But, in addition, the for loop
provides specific locations to contain an initialization and an increase expression,
executed before the loop begins the first time, and after each iteration, respectively.
Therefore, it is especially useful to use counter variables as condition. It works in
the following way:
1. Initialization is executed. Generally, this declares a counter variable, and sets
it to some initial value. This is executed a single time, at the beginning of the
loop.
2. Condition is checked. If it is true, the loop continues; otherwise, the loop
ends, and statement is skipped, going directly to step 5.
3. Statement is executed. As usual, it can be either a single statement or a block
enclosed in curly braces { }.
4. Increase is executed, and the loop gets back to step 2.
5. The loop ends: execution continues by the next statement after it.
1
2
3
4
5
6
7
8
9
10
11

// countdown using a for loop


#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "liftoff!\n";}

Here
is
the
Assignmetns:
i.
ii.

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!

countdown

example

using

for

Study about the while and do-while loops


Write a program to print first ten natural numbers using for loop.

loop:

iii.
iv.
v.

Write a program to print a table of a given number using for loop.


Write a program to calculate the sum of odd numbers from 1 to 10 and then
print the sum on the screen.
Write a program to calculate the factorial of a given number.

Introduction of MATLAB
OBJECTIVE:
To understand the basic features of MATLAB.

EQUIPMENT AND SOFTWARE:


Personal Computer loaded with MATLAB
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical
software package, which is used extensively in both academia and industry. It is an
interactive program for numerical computation and data visualization, which along
with its programming capabilities provides a very useful tool for almost all areas of
science and engineering.
As you might guess from its name, MATLAB deals mainly with matrices. A scalar
is a 1-by-1 matrix and a row vector of length say 5, is a 1-by-5 matrix.. One of the
many advantages of MATLAB is the natural notation used. It looks a lot like the
notation that you encounter in a linear algebra. This makes the use of the program
especially easy and it is what makes MATLAB a natural choice for numerical
computations. The purpose of this experiment is to familiarize MATLAB, by
introducing the basic features and commands of the program.
MATLAB is case-sensitive, which means that a + B is not the same as a + b.
The MATLAB environment allows the user to:
Manage variables
Import and export data
Perform calculations
Generate plots
Develop and manage files for use with MATLAB.

To start MATLAB:
START > PROGRAMS >MATLAB (folder) > MATLAB
Or shortcut creation/activation on the deskto

Display Windows is shown following.

Getting Help:
Type one of following commands in the command window:

help lists all the help topic


help topic provides help for the specified topic
help command provides help for the specified command
help help provides information on use of the help command
helpwin opens a separate help window for navigation

Variables:
Variable names:
Must start with a letter

May contain only letters, digits, and the underscore _


Matlab is case sensitive, i.e. one & OnE are different variables.
Matlab only recognizes the first 31 characters in a variable name.
Assignment statement:
Variable = number;
Variable = expression;
Example:
>> Tutorial = 1234;
>> Tutorial = 1234
Tutorial =
1234

NOTE: when a semi-colon


; is placed at the end of
each command, the result is
not displayed.

Special variables:

ans : default variable name for the result


pi: = 3.1415926
eps: = 2.2204e-016, smallest amount by which 2 numbers can differ.
Inf or inf : , infinity
NaN or nan: not-a-number

Commands involving variables:

who: lists the names of defined variables


whos: lists the names and sizes of defined variables
clear: clears all varialbes, reset the default values of special variables.
clear name: clears the variable name
clc: clears the command window
clf: clears the current figure and the graph window.

Assignments:
i.

Write a program which performs all arithmetic operations between two


variables.

ii.
iii.
iv.
v.

Write a program which perform square root of a number.


Write a program which performs loop operations
Write a program in which all operations should be performed which are
defining in the previous syntax...
Solve the following equations
Y= x2+3x+1;
Y= Sin(x) + 2y;
Y= Sin(x) + Cos(x) + Tan(x);

Introduction to Vectors in Matlab


OBJECTIVE:

To understand about the vectors and different operations on vectors in


MATLAB.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
Almost all of Matlabs basic commands revolve around the use of vectors. A vector
is defined by placing a sequence of numbers within square braces:
>> v = [3 1]
v=

This creates a row vector which has the label v. The first entry in the vector is a
3 and the second entry is a 1. Note that matlab printed out a copy of the vector after
you hit the enter key. If you do not want to print out the result put a semi-colon at
the end of the line:
>> v = [3 1];
>>
If you want to view the vector just type its label:
>> v
v=

You can define a vector of any size in this manner:


>> v = [3 1 7 -21 5 6]
v=3

-21

Notice, though, that this always creates a row vector. If you want to create a
column vector you need to take the transpose of a row vector. The transpose is
defined using an apostrophe ():
>> v = [3 1 7 -21 5 6]'
v=
3
1
7
-21
5
6
A common task is to create a large vector with numbers that fit a repetitive pattern.
Matlab can define a set of numbers with a common increment using colons. For
example, to define a vector whose first entry is 1, the second entry is 2, the third
is 3, and sequentially through 8, you enter the following:
>> v = [1:8]
v=

If you wish to use an increment other than one that you have to define the start
number, the value of the increment, and the last number. For example, to define a
vector that starts with 2 and ends in 4 with steps of 0.25 you enter the following:
>> v = [2:.25:4]
v=
Columns 1 through 7
2.0000

2.2500

2.5000

2.7500

3.0000

3.2500

3.5000

Columns 8 through 9
3.7500

4.0000

Accessing elements within a vector:


You can view individual entries in this vector. For example to view the first entry
just type in the following:
>> v (1)
Ans =

This command prints out entry 1 in the vector. Also notice that a new variable
called ans has been created. Any time you perform an action that does not include
an assignment matlab will put the label ans on the result.
To simplify the creation of large vectors, you can define a vector by specifying the
first entry, an increment, and the last entry. Matlab will automatically figure out
how many entries you need and their values. For example, to create a vector whose
entries are 0, 2, 4, 6, and 8, you can type in the following line:
>> 0:2:8
ans =

Matlab also keeps track of the last result. In the previous example, a variable ans is
created. To look at the transpose of the previous result, enter the following:
>> ans'
ans =
0
2
4
6
8

To be able to keep track of the vectors you create, you can give them names. For
example, a row vector v can be created:
>> v = [0:2:8]
v=

>> v
v=
>> v;
>> v'
ans =
0
2
4
6
8
Note that in the previous example, if you end the line with a semi- colon, the result
is not displayed. This will come in handy later when you want to use Matlab to
work with very large systems of equations.
Matlab will allow you to look at specific parts of the vector. If you want to only
look at the first three entries in a vector you can use the same notation you used to
create the vector:
>> v(1:3)
ans = 0

>> v(1:2:4)

ans =

>> v(1:2:4)'
ans =
0
4
Basic operations on vectors:
Once you master the notation you are free to perform other operations:
>> v(1:3)-v(2:4)
ans =

-2

-2

-2

For the most part Matlab follows the standard notation used in linear algebra. We
will see later that there are some extensions to make some operations easier. For
now, though, both addition subtraction are defined in the standard way. For
example, to define a new vector with the numbers from 0 to -4 in steps of -1 we do
the following:
>> u = [0:-1:4]
u = [0:-1:-4]
u=

-1

-2

-3

-4

We can now add u and v together in the standard way:


>> u+v
ans =

Additionally, scalar multiplication is defined in the standard way. Also note that
scalar division is defined in a way that is consistent with scalar multiplication:
>> -2*u
ans =

>> v/3
ans =

0.6667

1.3333

2.0000

2.6667

With these definitions linear combinations of vectors can be easily defined and the
basic operations combined:
>> -2*u+v/3
ans =

2.6667

5.3333

8.0000 10.6667

You will need to be careful. These operations can only be carried out when the
dimensions of the vectors allow it. You will likely get used to seeing the following
error message which follows from adding two vectors whose dimensions are
different:
>> u+v'
??? Error using ==> plus
Matrix dimensions must agree.
Some useful commands:

Assignments:
Write a program in which user intialize two vectors and perform following
operations

a.
b.
c.
d.
e.
f.
g.
h.

Addition
Multiplication
Subtraction
Division
Sin
Log
Transpose of all results
Find the length of vectors

Introduction to Matrix in Matlab


OBJECTIVE:

To understand about the Matrix and different operations on Matrix in


MATLAB.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
A Matrix array is two-dimensional, having both multiple rows and multiple
columns, Similar to vector arrays:
It begins with [, and end with ]
Spaces or commas are used to separate elements in a row
Semicolon or enter is used to separate rows.
Example:
>> f = [1 2 3; 4 5 6]
f=
123
456
>> h = [ 2 4 6
1 3 5]
h=
246
135
Magic Function:
For example you can generate a matrix by entering

>> m=magic(4)
It generates a matrix whose elements are such that the sum of all elements in its
rows, columns and diagonal elements are same
Sum Function:
You can verify the above magic square by entering
>> sum(m)
For rows take the transpose and then take the sum
>> sum(m)
Diag:
You can get the diagonal elements of a matrix by entering
>> d=diag(m)
>> sum(d)
Matrix Addressing:
matrixname(row, column)
colon may be used in place of a row or column reference to select the
entire row or column.
Example:

Recall:

>> f(2,3)

f=

ans =6

123

>> h(:,1)
ans =2
1

456

Bold are the answers of the matrices...

h=

246

135
Some useful commands:
zeros(n): returns a n x n matrix of zeros

zeros(m,n): returns a m x n matrix of zeros


ones(n): returns a n x n matrix of ones
ones(m,n): returns a m x n matrix of ones
rand(n): returns a n x n matrix of random number
rand(m,n): returns a m x n matrix of random number
size (A): for a m x n matrix A, returns the row vector [m,n] containing the number
of rows and columns in matrix.
length(A): returns the larger of the number of rows or columns in A.
Some other useful commands given below

Assignments:
Write a program in which user take two matrices and perform following
operations...

Transpose
Scalar Multiplication
Matrix Multiplication
Matrix Inverse
Matrix Powers
Determinant
Identity Matrix
Addition and subtraction

Linear Equations and Eigenvalues


OBJECTIVE:

To understand about the linear Equation and Eigenvalues and solved these
using MATLAB.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
Eigenvalues:
For the transformation matrix

The vector

is an eigenvector with eigenvalue 2. Indeed,

On the other hand the vector

is not an eigenvector, since

And this vector is not a multiple of the original vector .


Another example

For the matrix

We have

Therefore, the vectors


and
are eigenvectors of
corresponding to the eigenvalues 1 and 3 respectively. (Here the symbol
indicates matrix transposition, in this case turning the row vectors into column
vectors.)
Linear Equation:
Example: a system of 3 linear equations with 3 unknowns (x 1, x 2, x 3):
3x 1 + 2x 2 x 3 = 10
-x 1 + 3x 2 + 2x 3 = 5
x 1 x 2 x 3 = -1

Let :

Then, the system can be described as:


Ax = b
Solution by Matrix Inverse:
Ax = b
A -1 Ax = A -1 b
x = A -1 b
MATLAB:
>> A = [3 2 -1; -1 3 2; 1 -1 -1];
>> b = [10; 5; -1];
>> x = inv (A)*b
x=
-2.0000
5.0000
-6.0000
Answer:
X 1 = -2, x 2 = 5, x 3 = -6
NOTE:
Left division: A\b >> b A

Solution by Matrix Division:


The solution to the equation

Ax = b

Can be computed using left division.


MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> b = [ 10; 5; -1];
>> x = A\b
x=
-2.0000
5.0000
-6.0000
Answer:
x 1 = -2, x 2 = 5, x 3 = -6
Assignments:
Write three to four programs for different linear equations and also find
Eigenvalues of these matrices

Plotting in MATLAB

OBJECTIVE:
To understand about the graphs plotting using MATLAB.
EQUIPMENT AND SOFTWARE:
Personal Computer loaded with MATLAB
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
For more information on 2-D plotting, type help graph2d
Plotting a point:
>> plot ( variablename, symbol)
The function plot () creates a graphics window, called a Figure window, and named
by default Figure No. 1
Example:
Complex number
>> z = 1 + 0.5j;
>> plot (z, .)
Commands for axes:

Plotting Curves:

plot (x,y) generates a linear plot of the values of x (horizontal axis) and y
(vertical axis).
semilogx (x,y) generate a plot of the values of x and y using a logarithmic scale
for x and a linear scale for y
semilogy (x,y) generate a plot of the values of x and y using a linear scale for x
and a logarithmic scale for y.
loglog(x,y) generate a plot of the values of x and y using logarithmic scales for
both x and y
Multiple Curves:
plot (x, y, w, z) multiple curves can be plotted on the same graph by using
multiple arguments in a plot command. The variables x, y, w, and z are vectors.
Two curves will be plotted: y vs. x, and z vs. w.
legend (string1, string2,) used to distinguish between plots on the same
graph
Multiple Figures:
figure (n) used in creation of multiple plot windows. place this command before
the plot() command, and the corresponding figure will be labeled as Figure n
close closes the figure n window.
close all closes all the figure windows.
Subplots:
subplot (m, n, p) m by n grid of windows, with p specifying the current plot as
the p th window
Example: (polynomial function)
plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, &
log/log scale:
y = 2x 2 + 7x + 9

% Generate the polynomial:


x = linspace (0, 10, 100);
y = 2*x.^2 + 7*x + 9;
% plotting the polynomial:
figure (1);
subplot (2,2,1), plot (x,y);
title ('Polynomial, linear/linear scale');
ylabel ('y'), grid;
subplot (2,2,2), semilogx (x,y);
title ('Polynomial, log/linear scale');
ylabel ('y'), grid;
subplot (2,2,3), semilogy (x,y);
title ('Polynomial, linear/log scale');
xlabel('x'), ylabel ('y'), grid;
subplot (2,2,4), loglog (x,y);
title ('Polynomial, log/log scale');
xlabel('x'), ylabel ('y'), grid;
Adding new curves to the existing graph:
Use the hold command to add lines/points to an existing plot.
hold on retain existing axes, add new curves to current axes. Axes are
rescaled when necessary.
hold off release the current figure window for new plots
Grids and Labels:

Additional commands for plotting:


Assignmetns:
Use Matlab command to obtain the following
i.
ii.
iii.

Extract the fourth row of the matrix generated by magic(6)


Show the results of x multiply by y and y divides by x.
Given x = [0:0.1:1.1] and y = [10:21]
Generate random matrix r of size 4 by 5 with number varying between -8
and 9
Use MATLAB commands to get exactly as the figure shown below
x=pi/2:pi/10:2*pi;
y=sin(x);

z=cos(x);

Polynomials in MATLAB
OBJECTIVE:
The objective of this session is to learn how to represent polynomials in
MATLAB, find roots of polynomials, create polynomials when roots are known
and obtain partial fractions.

EQUIPMENT AND SOFTWARE:


Personal Computer loaded with MATLAB
OPERATING SYSTEM:
Windows XP, Windows 7, Windows 8 etc...
THEORY:
MATLAB provides functions for standard polynomial operations, such as
polynomial roots, evaluation, and differentiation. In addition, there are functions
for more advanced applications, such as partial fraction expansion.
Polynomial Function Summary:
Function
Conv
Deconv
Poly
Polyder
Polyval
Polyvalm
Residue
Roots

Description
Multiply polynomials
Divide polynomials
Polynomial with specified roots
Polynomial derivative
Polynomial evaluation
Matrix polynomial evaluation
Partial-fraction expansion (residues)
Find polynomial roots

Representing Polynomials:
MATLAB represents polynomials as row vectors containing coefficients ordered
by descending powers. For example, consider the equation

To enter this polynomial


>>p = [1 0 -2 -5];
Polynomial Roots:
The roots function calculates the roots of a polynomial:
>>r = roots(p)

into MATLAB, use

r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i
By convention, MATLAB stores roots in column vectors. The function poly returns
to the polynomial coefficients:
>>p2 = poly(r)
p2 =
1 8.8818e-16 -2 -5
Note: poly and roots are inverse functions
Polynomial Evaluation:
The polyval function evaluates a polynomial at a specified value. To evaluate p at
s= 5, use
>>polyval(p,5)
ans =
110
It is also possible to evaluate a polynomial in a matrix sense. In this case the
equation p(x) = x3-2x-5 becomes p(X) = X3-2X-5I, where X is a square matrix and
I is the identity matrix
For example, create a square matrix X and evaluate the polynomial p at X:
>>X = [2 4 5; -1 0 3; 7 1 5];
>>Y = polyvalm(p,X)
Y=
377 179 439

111 81 136
490 253 639
Convolution and Deconvolution:
Polynomial multiplication and division correspond to the operations convolution
and deconvolution. The functions conv and deconv implement these operations.
Consider the polynomials a(s) = s2+2s+3 and b(s) = 4s2+5s+6. To compute their
product,
>>a = [1 2 3]; b = [4 5 6];
>>c = conv(a,b)
c=
4 13 28 27 18
Use deconvolution to divide back out of the product:
>>[q,r] = deconv(c,a)
q=
456

r=
00000
Polynomial Derivatives:
The polyder function computes the derivative of any polynomial. To obtain the
derivative of the polynomial
>>p= [1 0 -2 -5]
>>q = polyder(p)
q=

3 0 -2
polyder also computes the derivative of the product or quotient of two
polynomials. For example, create two polynomials a and b:
>>a = [1 3 5];
>>b = [2 4 6];
Calculate the derivative of the product a*b by calling polyder with a single output
argument:
>>c = polyder(a,b)
c=
8 30 56 38
Calculate the derivative of the quotient a/b by calling polyder with two output
arguments:
>>[q,d] = polyder(a,b)
q=
-2 -8 -2
d=
4 16 40 48 36
q/d is the result of the operation.
Partial Fraction Expansion:
residue finds the partial fraction expansion of the ratio of two polynomials. This
is particularly useful for applications that represent systems in transfer function
form. For polynomials b and a,

If there are no multiple roots, where r is a column vector of residues, p is a column


vector of pole locations, and k is a row vector of direct terms.
Consider the transfer function
>>b = [-4 8];
>>a = [1 6 8];
>>[r, p, k] = residue(b,a)
r=
-12
8
p=
-4
-2
k=
[]
Given three input arguments (r, p, and k), residue converts back to polynomial
form:
>>[b2,a2] = residue(r,p,k)
b2 =
-4 8
a2 =
168
Assignments:

Anda mungkin juga menyukai