Sei sulla pagina 1di 15

MTS-362

Control Engineering Lab-2


Introduction to MATLAB its functions and applications
Plotting, Curve Fitting (Part-II)
2.0 Plotting:
The simplest graphs to create are plots of points in the cartesian plane. For example:
>> x = [1;2;3;4;5];
>> y = [0;.25;3;1.5;2];
>> plot(x,y)
The resulting graph is displayed in Figure

Figure 2.1: A simple Matlab graph


Notice that, by default, Matlab connects the points with straight line segments. An alternative
is the following ():
>> plot(x,y,'o')

Control Engineering Lab

1/15

Figure 2.2: Another simple Matlab graph


All Matlab variables must have numerical values:
>> x = -10:.1:10;
The basic plot command:
>> plot(sin(x))

Figure 2.3: Graph of Sine


Note that the horizontal axis is marked according to the index, not
the value of x. Fix this as follows:
Control Engineering Lab

2/15

>> plot( x, sin(x) )

Figure 2.4: Another Sine curve


This is the same thing as plotting "parametric curves."
We can plot the "inverse relationship" (for example, the squaring function and +/- square root)
easily:
>> plot( x, x.^2 )

Control Engineering Lab

>> plot( x.^2, x )

3/15

or a spiral in two or in three dimensions:


>> t = 0:.1:10; plot( t .*
cos(t), t .* sin(t) )

>> plot3( t .* cos(t), t .*


sin(t), t )

Plot several curves simultaneously with plot(x1, y1, x2,


y2, ...):
>> plot( x, cos(x), x, 1 - x.^2./2, x, 1 x.^2./2 + x.^4./24 )

Control Engineering Lab

4/15

Figure 2.5:

2.1 Putting several graphs in one window


The subplot command creates several plots in a single window. To be precise,
subplot(m,n,i) creates mn plots, arranged in an array with m rows and n columns. It
also sets the next plot command to go to the ith coordinate system (counting across the rows).
Here is an example
>>
>>
>>
>>
>>
>>
>>
>>
>>

2.2

t = (0:.1:2*pi)';
subplot(2,2,1)
plot(t,sin(t))
subplot(2,2,2)
plot(t,cos(t))
subplot(2,2,3)
plot(t,exp(t))
subplot(2,2,4)
plot(t,1./(1+t.^2))

How to plot in DIFFERENT COLORS

If you have hard time seeing some of the plots that you do in
matlab on the color workstations, you should probably change
the colors.
To find out how to do that, you can type at the matlab prompt:
Control Engineering Lab

5/15

help plot
In short, color can be specified inside the plot command.
can type:

You

plot(x,y,'w')
to plot a white line. You can also use other colors -- they
are all listed in the plot help information.

2.3

Some more about plotting

Here are other ways to graph multiple curves, using matrices (plotted by
columns) and using "hold."

Figure 2.6:
Functions of two variables may be plotted, as well, but some "setup" is required!
>> [x y] = meshgrid(-3:.1:3, -3:.1:3);
>> z = x.^2 - y.^2;
Here are two options for plotting the surface. Look at the help page for details.
Control Engineering Lab

6/15

Figure 2.7:

2.4

3D Plots:

In order to create a graph of a surface in 3-space (or a contour plot of a surface), it is


necessary to evaluate the function on a regular rectangular grid. This can be done using the
meshgrid command. First, create 1D vectors describing the grids in the x- and y-directions:
>> x = (0:2*pi/20:2*pi)';
>> y = (0:4*pi/40:4*pi)';
Next, ``spread'' these grids into two dimensions using meshgrid:
>> [X,Y] = meshgrid(x,y);
>> whos
Name
Size
Bytes
X
Y
x
y

41x21
41x21
21x1
41x1

6888
6888
168
328

Class
double
double
double
double

array
array
array
array

Grand total is 1784 elements using 14272 bytes


The effect of meshgrid is to create a vector X with the x-grid along each row, and a vector Y
with the y-grid along each column. Then, using vectorized functions and/or operators, it is
easy to evaluate a function z = f(x,y) of two variables on the rectangular grid:
>> z = cos(X).*cos(2*Y);
Having created the matrix containing the samples of the function, the surface can be graphed
using either the mesh or the surf commands :
Control Engineering Lab

7/15

>> mesh(x,y,z)
>> surf(x,y,z)

Figure 2.8: Using the mesh command

Figure 2.9: Using the surf command


(The difference is that surf shades the surface, while mesh does not.) In addition, a contour
plot can be created :
>> contour(x,y,z)
Control Engineering Lab

8/15

2.5

Some More about Plotting and Graphs

plot(x,y) creates a Cartesian plot of the vectors x & y


plot(y)
creates a plot of y vs. the numerical values of the
elements in the y-vector.
semilogx(x,y) plots log(x) vs y
semilogy(x,y)

plots x vs log(y)

loglog(x,y)

plots log(x) vs log(y)

grid

creates a grid on the graphics plot

title('text')

places a title at top of graphics plot

xlabel('text') writes 'text' beneath the x-axis of a plot


ylabel('text') writes 'text' beside the y-axis of a plot
text(x,y,'text')

writes 'text' at the location (x,y)

text(x,y,'text','sc') writes 'text' at point x,y assuming


lower left corner is (0,0) and upper right corner is
(1,1).

Control Engineering Lab

9/15

polar(theta,r) creates a polar plot of the vectors r &


theta where theta is in radians.
bar(x) creates a bar graph of the vector x. (Note also the
command stairs(x).)
bar(x,y)

creates a bar-graph of the elements of the vector


y, locating the bars according to the vector
elements of 'x'. (Note also the command
stairs(x,y).)

Polar plots:
angle = 0:.1*pi:3*pi;
radius = exp(angle/20);
polar(angle,radius),...
title('An Example Polar Plot'),...
grid
Bar graph:
bar(x,y) and bar(y)
stair (x,y) and stair(y)
Multiple plots:
x1=0:.05*pi:pi;
y1=sin(x1);
plot(x1,y1)
hold
y2=cos(x1);
plot(x1,y2)
You can create multiple graphs by using multiple arguments.
In addition to the vectors x,y created earlier, create the
vectors a,b and plot both vector sets simultaneously as
follows.
a = 1 : .1 : 3;
b = 10*exp(-a);
plot(x,y,a,b)
Multiple plots can be accomplished also by using matrices
rather than simple vectors in the argument. If the arguments
of the 'plot' command are matrices, the COLUMNS of y are
plotted on the ordinate against the COLUMNS of x on the
abscissa.

Control Engineering Lab

10/15

2.6

EQUATION FITTING

Many occasions arise when we have a set of (x,y) pairs


and we desire to find an equation or function that "fits"
these data. The procedure we follow can be generally
classified in one of two categories, interpolating functions
or least squares functions.
The least-squares function is one that obtains the best
fit, where the meaning here of "best" is based on minimizing
the sum of the squares of the differences between the function
and the data pairs. Clearly the idea of "least squares" is to
achieve some sort of average or mean value function whose
graphical curve does not typically pass through any of the
(x,y) data pairs. It is
appropriate for experimental data in which every data pair is
obtained under conditions of uncertainty and for which any
collected data, as a consequence of experimental error, may be
greater or less than the true value.
2.7

INTERPOLATING POLYNOMIAL

The interpolating function is one that satisfies every


data point exactly.
When viewed in a graphical plot, the
interpolating function passes through each data point. If for
convenience we select the polynomial form as the function, a
polynomial of degree 'n' can be found for a set of 'n+1' (x,y)
data pairs. The general form of the polynomial can be written
y = a0 + a1x + a2x2 + a3x3 + ....... + anxn
To evaluate the interpolating polynomial of degree 'n' for any
data set, we must evaluate 'n+1' coefficients, a0, a1, a2, a3,
.....an. Given the 'n+1' (x,y) data pairs, we can form 'n+1'
equations
y1
y2
y3

= a0 + a1x1
= a0 + a1x2
= a0 + a1x3
.
.
.
.
.
.
.
.
.

yn+1 = a0 + a1xn+1

+
+
+

a2x12
a2x22
a2x32
.
.
.

+
+
+

a3x13 + ...... + anx1n


a3x23 + ...... + anx2n
a3x33 + ...... + anx3n
.
.
.
.
.
.

a2xn+12

a3xn+13 + ... + anxn+1n

This is a solvable set of 'n+1' equations with 'n+1' unknowns.


The unknowns are the coefficients a0, a1,......an.
If there
exists only two or three equations, the solution procedure for
Control Engineering Lab

11/15

the unknown coefficients can conveniently follow Cramer's


Rule.
In general, however, it is common to rely on matrix
algebra to manipulate these equations into a format for which
n operations of back substitution will obtain the unknown
coefficients. Here we will simply rely on the methods of right
(or left) division in 'matlab' to obtain the unknown
coefficients, leaving the details of the numerical method for
back substitution for later discussion.
Note that the set of equations can be conveniently
expressed by the matrix equation
[y] = [X][a]
where
y1
y2
[y] =

x1

x12.....x1n+1

x2

x22.....x2n+1

[X] =
y3
.
.
.
yn+1

a1
a2
[a] =

1
.
.
.
1

x3
.
.
.
xn+1

x32.....x3n+1
.
.
.
.
.
.
xn+12... xn+1n+1

a3
.
.
.
an+1

Note that the right side of the matrix equation must be the
product of a 'n+1' x 'n+1' square matrix times a 'n+1' x 1
column matrix! The solution using Gauss elimination calls for
left division in 'matlab' or
[a] = [X]\[y]
Using this method, we can find the coefficients for a ndegree polynomial that passes exactly through 'n+1' data
points.
If we have a large data set, each data pair including
some experimental error, the n-degree polynomial is NOT A GOOD
CHOICE. Polynomials of degree larger than five or six often
have terribly unrealistic behavior BETWEEN the data points
even though the polynomial curve passes through every data
point ! As an example, consider these data.
x

2
3
4

4
3
5

Control Engineering Lab

12/15

5
6
7
8
9
10

4
7
5
7
10
9

There are 9 data points in this set. It is clear that as x


increases, so also does y increase; however, it appears to be
doing so in a nonlinear way. Let's see what the data looks
like. In 'matlab', create two vectors for these data.
x9 = [2:1:10];
y9 = [ 4 3 5 4 7 5 7 10 9 ];
To observe these data plotted as points, execute
plot(x9,y9,'o')
Because we have nine data pairs, it is possible to construct
an eighth-degree interpolating polynomial.
y = a0 + a1x + a2x2 + a3x3 + ....... + a8x8
To find the unknown coefficients, define the column vector y
y = y9'
and the matrix X
X =
[ones(1,9);x9;x9.^2;x9.^3;x9.^4;x9.^5;x9.^6;x9.^7;x9.^8]'
Note that X is defined using the transpose, the
function and the array operator ' .^ '. With X and
defined, they satisfy the equation

ones()
y
so

[X][a] = [y]
Solve for the coefficients, matrix
entering the command

a in the aboveequation, by

a = X\y
which results in

Control Engineering Lab

13/15

a = [ 1.0e+003*
3.8140
-6.6204
4.7831
-1.8859
.4457
- .0649
.0057
- .0003
.0000 ]
Note that the ninth coefficient a(8) appears to be zero.
Actually, it is finite, it only appears to be zero because
'matlab' is printing only 4 significant figures to the left of
the decimal point. To observe the coefficients with more
significant figures, enter the commands
format long
a
and the format is changed to one with 15 significant digits.
Clearly a(8) is not zero, it is a small number because it is
multiplying a number, x, raised to the eight power.
Now that we have the coefficients, let's generate a sufficient
number of points to create a smooth curve. For x, form a
vector over the range 2 <= x <= 10 in increments of 0.1.
x = [ 2:.1:10 ];
For y, calculate the value of the eighth degree polynomial for
each x.
y =a(1)+ a(2).*x + a(3).*x.^2 + a(4).*x.^3 +
a(5).*x.^4...
+ a(6).*x.^5 + a(7).*x.^6 + a(8).*x.^7 + a(9).*x.^8;
Now plot (x,y) and the data points (x9,y9).
plot(x,y,x9,y9,'o')
The polynomial results appear to pass exactly through every
data point, but clearly the polynomial is useless for
representing our impression of the data at any other point
within the range of x!
This is a common behavior for highorder interpolating polynomials. For this reason, one should
never attempt to use high order interpolating polynomials to
represent experimental data.
Control Engineering Lab

14/15

Lab Task
Plot all trigonometry, exponential and any polynomial function
using subplot, mesh, surf, plot

Control Engineering Lab

15/15

Potrebbero piacerti anche