Lecture Slides: Dr. Nasir M. Mirza

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 38

Lecture Slides

Lecture: Introduction to Matlab


Part – b

Dr. Nasir M. Mirza


Email: nmm@pieas.edu.pk
Creating a 2D Plot
For example, these statements use the colon operator to create a vector
of x values ranging from 0 to 2, compute the sine of these values, and
plot the result:

x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y,'LineWidth',3)
Now label the axes and add a title. The characters \pi create the symbol .
See text strings for more symbols:
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the Sine
Function','FontSize',12)
Graph is on
next page
Creating a 2D Plot
Result of the example
Plotting Elementary Functions
Example of a graph ploting with labels and text and grid.

% prog2.m
t = -1 : 0.01 : 1;
f = 4.5*cos(2*pi*t - pi/6);
plot(t,f 'LineWidth',3),title('Fig.2a');
axis([-1, 1, -6, 6]);
xlabel('time, t');
ylabel('f(t)');
text(-0.6, 5,' f(t) = A cos(wt + phi)');
grid; Graph is on
next page
Plotting Elementary Functions
Resulting
graph
Specifying the Color and Size of Markers
You can also specify line characteristics using graphics properties:
LineWidth -- Specifies the width (in points) of the line.
MarkerEdgeColor -- Specifies the color of the marker or the edge color
for filled markers (circle, square, diamond, pentagram, hexagram,
and the four triangles).
MarkerFaceColor -- Specifies the color of the face of filled markers.
MarkerSize -- Specifies the size of the marker in units of points.

t = 0:.4:50; Example:
alpha =.055; Prog3.m
y = exp(-alpha*t).*sin(.5*t)

plot(t,y,'--rs','LineWidth',3,...
'MarkerEdgeColor','k',... Graph is on
'MarkerFaceColor','g',... next page
'MarkerSize',10)
Specifying the Color and Size of Markers
Resulting
figure
Plotting commands
PLOT(X,Y) plots vector Y versus vector X.
TITLE('text') adds text at the top of the current plot.
XLABEL('text') adds text beside the X-axis on the current axis.
YLABEL('text') adds text beside the Y-axis on the current axis.
GRID, by itself, toggles the major grid lines of the current axes.
GTEXT('string') displays the graph window, puts up a cross-hair, and waits
for a mouse button or keyboard key to be pressed.
SUBPLOT(m,n,p), breaks the Figure window into an m-by-n matrix of small
or SUBPLOT(mnp), axes.
STEM(Y) stemDiscrete sequence or "stem" plot. STEM(Y) plots the
data sequence Y as stems from the x axis terminated with
circles for the data value.
SEMILOGX(...) is the same as PLOT(...), except a logarithmic (base 10)
scale is used for the X-axis.
SEMILOGY(...) is the same as PLOT(...), except a logarithmic (base 10)
scale is used for the Y-axis..
Multiple Graphs
Two ways to make multiple plots on a single graph are illustrated here.
Another way is with the hold command. The command hold freezes the
current graphics screen so that subsequent plots are superimposed on
it. Entering hold again releases the "hold". The commands hold on and
hold off are also available.
One can override the default line types and point types. For example,

% prog3.m
t = 0: 0.01: 2*pi;
y1 = sin(t);
y2 = sin(2*t);
y3 = sin(4*t); Graph is on
plot(t, y1, '--', y2, ‘*', y3, '+') next page
Multiple Graphs
Results
Plotting colors and line styles
Colors Line Styles
y yellow . point
M magenta o circle
C cyan x x-mark
R red + plus
G green - solid
B blue * star
W white : dotted
K black -. Dashdot
-- dashed
More mark types are; square(s), diamond(d), up-triangle(v), down-
triangle(^), left-triangle(<), right-triangle(>), pentagram(p),
hexagram(h)
See also help plot for more line and mark color.
Subplot
The command subplot can be used to partition the
screen so that up to four plots can be viewed
simultaneously. See help subplot.
Example for use of subplot:

% prog4.m
% Line plot of a chirp
x = 0 : 0.05 : 5;
y = sin(x.^2);
subplot(2,1,1), plot(x,y);
% Bar plot of a bell shaped curve
x = -2.9 : 0.2 : 2.9; Graph is on
subplot(2,1,2), bar(x,exp(-x.*x)); next page
subplots

Results
Various Plotting Functions:
MATLAB supports many types of graph and surface plots:

 2 dimensions line plots (x vs. y),


 filled plots,
 bar charts,
 pie charts, To preview some of these capabilities
 parametric plots, and others as well, enter the
 polar plots, command demos.
 contour plots,
 density plots,
 log axis plots,
 surface plots,
 parametric plots in 3 dimensions
 and spherical plots.
Line Plots of 3-D Data
The 3-D analog of the plot function is plot3. If x, y, and z are three
vectors of the same length,
plot3(x,y,z)
generates a line in 3-D through the points whose coordinates are the
elements of x, y, and z.
Then it produces a 2-D projection of that line on the screen. For
example, these statements produce a helix.

% prog5.m
t = 0:pi/50:10*pi;
plot3(sin(t),cos(t),t,'LineWidth',3) Graph is on
axis square; grid on next page
Line Plots of 3-D Data
Production of helix
3-D Plots
MATLAB Commands for Mesh and Surface
meshgrid: generate X and Y arrays for 3-D plots
mesh: draws a wireframe mesh
surf: plot a 3-D shaded surface
colorbar: add a color bar tool
patch: creating patch graphics objects
hidden: remove hidden lines from mesh plot
Three-D meshgrid
To illustrate the use of meshgrid, consider the sin(r)/r or sinc function.
To evaluate this function between -8 and 8 in both x and y, you need
pass only one vector argument to meshgrid, which is then used in
both directions.
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
The matrix R contains the distance from the center of the matrix, which
is the origin. Adding eps prevents the divide by zero (in the next step)
that produces Inf values in the data.
Forming the sinc function and plotting Z with mesh results in the 3-D
surface.
Z = sin(R)./R;
mesh(X,Y,Z)
Three-D meshgrid
Mesh and Surface (Example) (2)

Z = sin(R)./R; 1
mesh(X,Y,Z)

0.5

-0.5
10
10
0 0
-10 -10
Three-D meshgrid
Mesh and Surface
Integration by MATLAB

We seek to compute:
b

 f ( x)dx
a

If m is a point between a and b than:

b m b

 f ( x)dx   f ( x)dx   f ( x)dx


a a m

The value of the integral is the area under curve


Integration by MATLAB
Midpoint rule:
Approximation:

M  h  f (m),

h ba

ab
m
2
b
M   f ( x)dx
a
Integration by MATLAB
Trapezoid rule:
Approximation:

h ba
b
T   f ( x)dx
a

f ( a )  f (b)
T h ,
2
Integration by MATLAB
Simpson’s Rule
2 1
S M  T
3 3
h
S  ( f ( a )  4 f (t )  f (b))
6
Integration by MATLAB
MATLAB Example(1)
% Midpoint, Trapezoid and Simpson's approx.
% for the function sqrt(1-x^2) for two
subintervals
a = 0; b = 1;
h = (b - a); m = 1/2;
y0 = sqrt(1-a^2);
y1 = sqrt(1-m^2);
y2 = sqrt(1-b^2);
M = 2*h*y1; % mid-point rule
T = h*(y0+y2)/2; % trapezoidal rule
S = h*(y0+4*y1+y2)/3; % Simpson rule
I = quad('sqrt(1-x.^2)',0,1); % MATLAB
Random Numbers
Pseudorandom numbers
Random numbers (MATLAB)
By start up a fresh MATLAB
format long;
rand
ans =
0.814723686393179
The first MATLAB random number
All MATLAB users keep getting this same number
True random? – No.
Computers are (in principle) deterministic machines and will not exhibit
random behavior.
Pseudorandom numbers
MATLAB commands:
Y = rand (returns a pseudorandom)
Y = rand(n) returns an (n, n) – matrix of values derived as described above.
Y = rand(m,n) (returns an random (m, n) – matrix )
Example:
Set rand to its default initial state:
rand('state', 0);
Initialize rand to a different state each time:
rand('state', sum(100*clock));
Save the current state, generate 100 values, reset the state, and repeat the
sequence:
s = rand('state');
u1 = rand(100);
rand('state',s);
u2 = rand(100); % Contains exactly the same values as u1.
Pseudorandom numbers
Example 1:
Make a random choice between two equally probable alternatives:
if rand < .5
'heads'
else
'tails'
end

Example 2:
Generate a 3-by-4 pseudorandom matrix:
R = rand(3,4)
R=
0.2190 0.6793 0.5194 0.0535
0.0470 0.9347 0.8310 0.5297
0.6789 0.3835 0.0346 0.6711
Pseudorandom numbers
Example: Generate a uniform distribution of random numbers on a
specified interval [a,b]. To do this, multiply the output of rand by (b-a),
then add a. For example, to generate a 5-by-5 array of uniformly
distributed random numbers on the interval [10,50],
a = 10; b = 50;
x = a + (b-a) * rand(5)
x=
18.1106 10.6110 26.7460 43.5247 30.1125
17.9489 39.8714 43.8489 10.7856 38.3789
34.1517 27.8039 31.0061 37.2511 27.1557
20.8875 47.2726 18.1059 25.1792 22.1847
17.9526 28.6398 36.8855 43.2718 17.5861
Least square
Curve Fitting
Curve Fitting

Given a set of m data points (t i , yi ), i  1,2...m


with yi  y j i j
We seek to find a function y such that: y(t i )  yi

Curve Fitting (Solution):


Idea: model y by a linear combination of n basis functions:

y(t )  b11 (t )  ...  bnn (t )

y  Xb, with x i , j   i (t j )
Curve Fitting
Curve Fitting (Models)
Linear:
1 (t )  t ,  2 (t )  1,
y (t )  b1t  b2

Polynomial

 j (t )  t n  j , j  1,2,..., n
y (t )  b1t n 1  b2 t n  2  ...  bn 1t  bn
Polynomial Curve Fitting
polyfit finds the coefficients of a polynomial that fits a set of data in a least-
squares sense:
p = polyfit(x,y,n)
x and y are vectors containing the x and y data to be fitted, and n is the degree
of the polynomial to return. For example, consider the x – y test data:
x = [1 2 3 4 5 6 7 8 9];
y = [5.5 43.1 128 290.7 498.4 1090.6 2123.5 4212.8 8356];
A third degree polynomial that approx. fits the data is
p = polyfit(x,y,3)
p = -0.1917 31.5821 -60.3262 35.3400
Let us 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:5;
y2 = polyval(p,x2);
plot(x,y,'o',x2,y2)
grid on
Curve Fitting
x = [1 2 3 4 5 6 7 8 9];

y = [5.5 43.1 128 290.7 498.4 1090.6 2123.5 4212.8 8356];

p = polyfit(x,y,3)

x2 = 1 : 0.1 : 9;

y2 = polyval(p,x2);

plot(x,y,'o',x2,y2,'LineWidth',3)

grid on
Literature on MATLAB

1. Numerical Computing with Matlab;


http://www.mathworks.com/moler/chapters.html.

2. Applied Numerical Methods for Engineers: Using


MATLAB and C; Schilling, Harris, Thomson Engineering, 2000.

3. Introduction to MATLAB 7 for Engineers


Palm, McGraw-Hill, 2005
Toolbox
• Communications Toolbox
• Control System Toolbox
• Database Toolbox
• Model-Based Calibration Toolbox
• Neural Network Toolbox
• Optimization Toolbox
• Partial Differential Equation (PDE) Toolbox
• Signal Processing Toolbox
• Statistics Toolbox
• Symbolic Math Toolbox
• System Identification Toolbox
• Wavelet Toolbox
Demos
There are several on line
Demos and Examples.

You might also like