Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Lab Experiment 1

A-Introduction to MATLAB and PRACTICE different MATLAB functions


for polynomial operations and obtaining different types of plots in terms of
Control Systems.

Objectives: This lab gives an introduction to MATLAB in the first part. In second part, the lab
also provides tutorial of polynomials, plotting and programming aspect of MATLAB from
control systems view point.

List of Equipment/Software:
Following equipment/software is required:
 MATLAB
Introduction to MATLAB:

MATLAB is a high-performance, high-level language. It stands for Matrix Laboratory. It can be


used as a fancy calculator and allows you to easily work with entire matrices rather than one
number at a time. It is useful for anything that requires matrix and vector manipulations such as:
mathematical, scientific, engineering, statistical and financial problems and anything that
requires plotting/visualizing and analyzing data. MATLAB comes with a basic set of tools for
visualizing data and for performing calculations on matrices and vectors.

For specific technologies, MATLAB provides toolboxes, which add to the basic MATLAB
functionality. Some toolboxes include Image Processing Toolbox, Statistics Toolbox, Neural
Network Toolbox, Fuzzy Logic Toolbox, Signal Processing Toolbox, Wavelet Toolbox,
Financial Toolbox, Bioinformatics Toolbox, Database Toolbox.

MATLAB Graphical User Interface:

MATLAB's graphical interface is written in Java and should be look similar on any OS. It is
divided into 4 main parts:
1. Command Window—this is where you type commands. Output or error messages
usually appear here too.
2. Workspace window—as you define new variables, they should be listed here.
3. Command History window—this is where past commands are remembered. If you want
to re-run a previous command or to edit it you can drag it from this window to the
command window or double click to re-run it.
4. Current Directory window—shows the files in the Current Directory.

Basic Operation:

Vectors and matrices in MATLAB:

We create a vector in MATLAB by putting the elements within [] brackets.

Example: x=[ 1 2 3 4 5 6 7 8 9 10]

We can also create this vector by typing x=1:10. The vector (1 1.1 1.2 1.3 1.4 1.5) can be created
by typing x=[ 1 1.1 1.2 1.3 1.4 1.5 ] or by typing x=1:0.1:1.5.

Matrices can be created according to the following example. The matrix A= is


created by typing
A=[1 2 3 ; 4 5 6; 7 8 9],

i.e., rows are separated with semi-colons. If we want to use a specific element in a vector or a
matrix, study the following example:

Example:

x=[10 20 30]

A=[ 1 2 3 ; 4 5 6 ; 7 8 9]

x(2)

A(3,1)

Here we extracted the second element of the vector by typing the variable and the position within
parentheses. The same principle holds for matrices; the first number specifies the row of the
matrix, and the second number specifies the column of the matrix. Note that in MATLAB the
first index of a vector or matrix starts at 1, not 0 as is common with other programming
languages.

If the matrices (or vectors which are special cases of a matrices) are of the same dimensions then
matrix addition, matrix subtraction and scalar multiplication works just like we are used to.

Example: Type

x=[1 2 3]

y =[4 5 6]

a=2

x+y

x-y

a*x

and observe what happens.

If want to apply an operation such as squaring each element in a matrix we have to use a dot .
before the operation we wish to apply. Type the following commands in MATLAB.

x=1:10

x.^2
A=[1 2 3 ; 4 5 6 ; 7 8 9 ]

A.^2

A^2

and observe the result. The dot allows us to do operations elementwise. All built-in functions
such as sin, cos, exp and so on automatically act elementwise on a matrix. Type

y=[0 1/4 1/2 3/4 1]

y=pi*y

sin(y)

and observe the result.

Colon Operator:

The colon operator(:) can be used to select ranges or blocks of values.

By typing b and hitting return, you will see the values in b:

b=
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

If you only want a subset of b, for instance, the inner square, you can type: b(2:3,2:3)

ans =
6 7
10 11

Let's break down the b(2:3,2:3) a little. MATLAB is accessing row two to three (2:3) inclusive
and column two to three (2:3) inclusive. Other than that, we are looking at the
same (row,column) notation that you are used to.

Outside of the subscript notation, the colon operator will create a row vector containing the
integers in the range specified. For instance, typing 2:8 results in:

ans =
2 3 4 5 6 7 8

You can also specify an increment or decrement (as a middle argument) with the colon operator.
For instance, typing 1:2:8 results in:

ans =
1 3 5 7

In this case, the increment is 2. Effectively, you are getting all of the odd numbers between 1 and
8.

Using Semicolons (;)

In MATLAB, semicolons “;” have two main uses. They:

 define the end of row, etc. A=[1,2;3,4].

tell MATLAB not to display any output when you end a line with a semicolon ( ; ). This is
particularly useful when you generate large matrices or perform long scripted computations.

Polynomials in MATLAB:

Polynomial Overview:
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 curve fitting and partial fraction expansion.

Symbolic Math Toolbox contains additional specialized support for polynomial operations.

Representing Polynomials MATLAB represents polynomials as row vectors containing


coefficients ordered by descending powers. For example, consider the equation

p(x) = x3 – 2x – 5
This is the celebrated example Wallis used when he first represented Newton's method to the
French Academy. To enter this polynomial into MATLAB, use

>>p = [1 0 -2 -5];

Polynomial Roots:

The roots function calculates the roots of a polynomial:

>>r = roots(p)

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

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=
4 5 6

r=
0 0 0 0 0

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.

Plotting on MATLAB:

MATLAB has an excellent set of graphic tools. Plotting a given data set or the results of
computation is possible with very few commands. The plot function has different forms
depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of
the elements of y versus the index of the elements of y. if we specify two vectors, plot(x,y)
produces a graph of y versus x. The basic MATLAB graphing procedure, for example in 2D, is
to take a vector of x-coordinates, x=(x1; : : : : : xn), and a vector of y-coordinates, y=(y1; : : : : :
yn), locate the points (xi; yi), with i = 1; 2; : : : : : n and then join them by straight lines.
You need to prepare x and y in an identical array form; namely, x and y are both row arrays or
column arrays of the same length. If x and y are both matrices, then they must have equal size.
The plot function plots columns of y versus columns of x. If one of x or y is a vector and the
other is a matrix, then the matrix must have dimensions such that one of its dimensions equals
the vector length. If the number of matrix rows equals the vector length, then the plot function
plots each matrix column versus the vector. If the number of matrix columns equals the vector
length, then the function plots each matrix row versus the vector. If the matrix is square, then the
function plots each column versus the vector. If one of x or y is a scalar and the other is either a
scalar or a vector, then the plot function plots discrete points. However, to see the points you
must specify a marker symbol, for example, plot(x,y,'o').

Plot(x,y):

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

y = [3 -1 2 4 5 1];

>>plot(x,y)

Create single line plot:


Create x as a vector of linearly spaced values between 0 and 2π. Use an increment
of π/100 between the values. Create y as sine values of x. Create a line plot of the data.
>>x = 0:pi/100:2*pi;
>>y = sin(x);
>>plot(x,y)

Multiple lines plot:

Define x as 100 linearly spaced values between −2π and 2π. Define y1 and y2 as sine and cosine
values of x. Create a line plot of both sets of data.
x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
figure
plot(x,y1,x,y2)
Specific line style:

Plot three sine curves with a small phase shift between each line. Use the default line style for
the first line. Specify a dashed line style for the second line and a dotted line style for the third
line.
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);
figure
plot(x,y1,x,y2,'--',x,y3,':')
Display markers at specific data points:

Create a line plot and display markers at every fifth data point by specifying a marker symbol
and setting the MarkerIndices property as a name-value pair.
x = linspace(0,10);
y = sin(x);
plot(x,y,'-o','MarkerIndices',1:5:length(y))

Stem(y):

stem(y) plots the data sequence, y, as stems that extend from a baseline along the x-axis. The
data values are indicated by circles terminating each stem. If y is a vector, then the x-axis scale
ranges from 1 to length(y). If y is a matrix, then stem plots all elements in a row against the
same x value, and the x-axis scale ranges from 1 to the number of rows in y.
stem(x,y) plots the data sequence, y, at values specified by X. The X and Y inputs must be
vectors or matrices of the same size. Additionally, X can be a row or column vector and Y must
be a matrix with length(x) rows. If x and y are both vectors, then stem plots entries in y against
corresponding entries in x. If x is a vector and y is a matrix, then stem plots each column
of y against the set of values specified by x, such that all elements in a row of y are plotted
against the same value. If x and y are both matrices, then stem plots columns of y against
corresponding columns of x.
Create a stem plot of 50 data values between −2π and 2π.
figure
Y = linspace(-2*pi,2*pi,50);
stem(Y)
Plot two data series using a two-column matrix.
figure
X = linspace(0,2*pi,50)';
Y = [cos(X), 0.5*sin(X)];
stem(Y)

Plot 50 data values of cosine evaluated between 0 and 2π and specify the set of x values for the
stem plot.
figure
X = linspace(0,2*pi,50)';
Y = cos(X);
stem(X,Y)
Polynomial Curve Fitting:

The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares
sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree
polynomial, then we get the polynomial fitting the data by writing –
p = polyfit(x,y,n)

Example
Create a script file and type the following code.
x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data
p = polyfit(x,y,4) %get the polynomial
% Compute the values of the polyfit estimate over a finer range,
% Compute the values of the polyfit estimate over a finer range,
% and plot the estimate over the real data values for comparison:
x2 = 1:.1:6;
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on

When you run the file, MATLAB displays the following result −
p=
4.1056 -47.9607 222.2598 -362.7453 191.1250

And plots the following graph:


Post Lab Assignment:

Plot Different Waveforms (sinewave, triangular wave, sawtooth, ramp) on MATLAB.

You might also like