Computer programming ecgd2102 using matlab
This presentation is the property of its rightful owner.
Sponsored Links
1 / 67

Computer Programming (ECGD2102 ) Using MATLAB PowerPoint PPT Presentation


  • 87 Views
  • Uploaded on
  • Presentation posted in: General

Computer Programming (ECGD2102 ) Using MATLAB. Lecture (7): Plotting in MATLAB (Chapter 7) Plotting in MATLAB. Instructor: Eng. Eman Al.Swaity. Objectives ( CHAPTER (7):Plotting in MATLAB ). At the end of this lesson, you will be able to understand: Examine Plotting, including:

Download Presentation

Computer Programming (ECGD2102 ) Using MATLAB

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Computer programming ecgd2102 using matlab

Computer Programming(ECGD2102 ) Using MATLAB

Lecture (7): Plotting in MATLAB

(Chapter 7)

Plotting in MATLAB

Instructor:

Eng. Eman Al.Swaity


Objectives chapter 7 plotting in matlab

Objectives (CHAPTER (7):Plotting in MATLAB )

At the end of this lesson, you will be able to understand:

Examine Plotting, including:

  • Two-dimensional plots,

  • Modifying line styles, Marks, and colors.

  • Grids and modifying the axes.

  • Placing a text on a plot.

  • Obtaining numerical value from a plot.

    Using log and semi-log plots.

    Using Subplot function.


Introduction

Introduction

MATLAB has many functions and commands that can be used to create various types of plots.

In our class we will only create two dimensional x – y plots.


Example of a 2 d plot

EXAMPLE OF A 2-D PLOT

Legend

Plot title

y axis

label

Text

Tick-mark

Data symbol

x axis

label

Tick-mark label


Basic two dimensional plots

Basic Two-Dimensional Plots

TWO-DIMENSIONAL plot() COMMAND

The basic 2-D plot command is:

plot(x,y)

  • where x is a vector (one dimensional array), and y is a vector. Both vectors must have the same number of elements.

  • The plot command creates a single curve with the x values on the abscissa (horizontal axis) and the y values on the ordinate (vertical axis).

  • The curve is made from segments of lines that connect the points that are defined by the x and y coordinates of the elements in the two vectors.


Basic two dimensional plots1

Basic Two-Dimensional Plots

CREATING THE X AND Y VECTORS

  • If data is given, the information is entered as the elements of the vectors x and y.

  • If the values of y are determined by a function from the values of x, than a vector x is created first, and then the values of y are calculated for each value of x. The spacing (difference) between the elements of x must be such that the plotted curve will show the details of the function.


Basic two dimensional plots2

x

1

2

3

5

7

7.5

8

10

y

2

6.5

7

7

5.5

4

6

8

Basic Two-Dimensional Plots

PLOT OF GIVEN DATA

Given data:

A plot can be created by the commands shown below. This can be done in the Command Window, or by writing and then running a script file.

>> x=[1 2 3 5 7 7.5 8 10];

>> y=[2 6.5 7 7 5.5 4 6 8];

>> plot(x,y)

Once the plot command is executed, the Figure Window opens with the following plot.


Line styles markers and colors

Line Styles, Markers, and Colors

PLOT OF GIVEN DATA


Line styles markers and colors1

plot(x,y,’line specifiers’)

Line Styles, Markers, and Colors

LINE SPECIFIERS IN THE plot() COMMAND

  • Line specifiers can be added in the plot command to:

  • Specify the style of the line.

  • Specify the color of the line.

  • Specify the type of the markers (if markers are desired).


Line styles markers and colors2

plot(x,y,‘line specifiers’)

Line Styles, Markers, and Colors

LINE SPECIFIERS IN THE plot() COMMAND

Line SpecifierLineSpecifierMarkerSpecifier

StyleColorType

Solid - red r plus sign +

dotted : green gcircle o

dashed -- blue basterisk *

dash-dot -.Cyan cpoint .

magenta msquare s

yellow ydiamond d

black k


Line styles markers and colors3

Line Styles, Markers, and Colors

LINE SPECIFIERS IN THE plot() COMMAND

  • The specifiers are typed inside the plot() command as strings.

  • Within the string the specifiers can be typed in any order.

  • The specifiers are optional. This means that none, one, two, or all the three can be included in a command.

EXAMPLES:

plot(x,y)A solid blue line connects the points with no markers.

plot(x,y,’r’)A solid red line connects the points with no markers.

plot(x,y,’--y’)A yellow dashed line connects the points.

plot(x,y,’*’)The points are marked with * (no line between the

points.)

plot(x,y,’g:d’)A green dotted line connects the points which are

marked with diamond markers.


Line styles markers and colors4

Year

1988

1989

1990

1991

1992

1993

1994

Sales (M)

127

130

136

145

158

178

211

Line Specifiers:

dashed red line and asterisk markers.

Line Styles, Markers, and Colors

PLOT OF GIVEN DATA USING LINE SPECIFIERS IN THE plot() COMMAND

>> year = [1988:1:1994];

>> sales = [127, 130, 136, 145, 158, 178, 211];

>> plot(year,sales,'--r*')


Line styles markers and colors5

Line Styles, Markers, and Colors

PLOT OF GIVEN DATA USING LINE SPECIFIERS IN THE plot() COMMAND

Dashed red line and asterisk markers.


A plot of a function

A PLOT OF A FUNCTION

CREATING A PLOT OF A FUNCTION

Consider:

A script file for plotting the function is:

% A script file that creates a plot of

% the function: 3.5^(-0.5x)*cos(6x)

x = [-2:0.01:4];

y = 3.5.^(-0.5*x).*cos(6*x);

plot(x,y)

Creating a vector with spacing of 0.01.

Calculating a value of y

for each x.

Once the plot command is executed, the Figure Window opens with the following plot.


A plot of a function1

A PLOT OF A FUNCTION


A plot of a function2

A PLOT OF A FUNCTION

CREATING A PLOT OF A FUNCTION

If the vector x is created with large spacing, the graph is not accurate.

Below is the previous plot with spacing of 0.3.

x = [-2:0.3:4];

y = 3.5.^(-0.5*x).*cos(6*x);

plot(x,y)


The fplot command

THE fplot COMMAND

THE fplot COMMAND

The fplot command can be used to plot a function

with the form: y = f(x)

fplot(‘function’,limits)

  • The function is typed in as a string.

  • The limits is a vector with the domain of x, and optionally with limits of the y axis:

    [xmin,xmax] or [xmin,xmax,ymin,ymax]

  • Line specifiers can be added.


The fplot command1

THE fplot COMMAND

PLOT OF A FUNCTION WITH THE fplot() COMMAND

A plot of:

>> fplot('x^2 + 4 * sin(2*x) - 1', [-3 3])


Multiple graphs in the same plot

MULTIPLE GRAPHS IN THE SAME PLOT

PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT

Plotting two (or more) graphs in one plot:

  • Using the plot command.

  • 2. Using the holdon, hold off commands.


Multiple graphs in the same plot1

MULTIPLE GRAPHS IN THE SAME PLOT

USING THE plot() COMMAND TO PLOT

MULTIPLE GRAPHS IN THE SAME PLOT

plot(x,y,u,v,t,h)

  • Plots three graphs in the same plot:

  • y versus x, v versus u, and h versus t.

  • By default, MATLAB makes the curves in different colors.

  • Additional curves can be added.

  • The curves can have a specific style by adding specifiers after each pair, for example:

plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)


Multiple graphs in the same plot2

Plot of the function, and its first and second derivatives, for , all in the same plot.

MULTIPLE GRAPHS IN THE SAME PLOT

USING THE plot() COMMAND TO PLOT

MULTIPLE GRAPHS IN THE SAME PLOT

x = [-2:0.01:4];

y = 3*x.^3-26*x+6;

yd = 9*x.^2-26;

ydd = 18*x;

plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

vector x with the domain of the function.

Vector y with the function value at each x.

Vector yd with values of the first derivative.

Vector ydd with values of the second derivative.

Create three graphs, y vs. x (solid blue line), yd vs. x (dashed red line), and ydd vs. x (dotted black line) in the same figure.


Multiple graphs in the same plot3

MULTIPLE GRAPHS IN THE SAME PLOT

USING THE plot() COMMAND TO PLOT

MULTIPLE GRAPHS IN THE SAME PLOT


Multiple graphs in the same plot4

MULTIPLE GRAPHS IN THE SAME PLOT

USING THE hold on, hold off, COMMANDS

TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT

hold on Holds the current plot and all axis properties so that subsequent plot commands add to the existing plot.

hold off Returns to the default mode whereby plot commands erase the previous plots and reset all axis properties before drawing new plots.

This method is useful when all the information (vectors) used for the plotting is not available a the same time.


Multiple graphs in the same plot plots

Plot of the function, and its first and second derivatives, for all in the same plot.

MULTIPLE GRAPHS IN THE SAME PLOT Plots

USING THE hold on, hold off, COMMANDS

TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT

x = [-2:0.01:4];

y = 3*x.^3-26*x+6;

yd = 9*x.^2-26;

ydd = 18*x;

plot(x,y,'-b')

hold on

plot(x,yd,'--r')

plot(x,ydd,':k')

hold off

First graph is created.

Two more graphs are created.


Formatting plots

106

FORMATTING PLOTS

EXAMPLE OF A FORMATTED 2-D PLOT

Plot title

Legend

y axis

label

Text

Tick-mark

Data symbol

x axis

label

Tick-mark label


Formatting plots1

FORMATTING PLOTS

  • A plot can be formatted to have a required appearance.

  • With formatting you can:

  • Add title to the plot.

  • Add labels to axes.

  • Change range of the axes.

  • Add legend.

  • Add text blocks.

  • Add grid.


Formatting plots2

FORMATTING PLOTS

There are two methods to format a plot:

  • Formatting commands.

  • In this method commands, that make changes or additions to the plot, are entered after the plot() command. This can be done in the Command Window, or as part of a program in a script file.

  • Formatting the plot interactively in the Figure Window.

  • In this method the plot is formatted by clicking on the plot and using the menu to make changes or add details.


Formatting plots3

FORMATTING PLOTS

FORMATTING COMMANDS

title(‘string’)

Adds the string as a title at the top of the plot.

xlabel(‘string’)

Adds the string as a label to the x-axis.

ylabel(‘string’)

Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])

Sets the minimum and maximum limits of the x- and y-axes.


Formatting plots4

FORMATTING PLOTS

FORMATTING COMMANDS

legend(‘string1’,’string2’,’string3’,pos)

Creates a legend using the strings to label various curves (when several curves are in one plot). The location of the legend is specified by the mouse, or by pos value(-1,0,1,2,3,4)

text(x,y,’string’)

Places the string (text) on the plot at coordinate x,y relative to the plot axes.

gtext(‘string’)

Places the string (text) on the plot. When the command executes the figure window pops and the text location is clicked with the mouse.

-1

2

1

3

4


Formatting plots5

FORMATTING PLOTS

EXAMPLE OF A FORMATTED PLOT

Below is a script file of the formatted light intensity plot (2nd slide).

(Some of the formatting options were not covered in the lectures, but are described in the book)

x=[10:0.1:22];

y=95000./x.^2;

xd=[10:2:22];

yd=[950 640 460 340 250 180 140];

plot(x,y,'-','LineWidth',1.0)

hold on

plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)

hold off

Creating vector x for plotting the theoretical curve.

Creating vector y for plotting the theoretical curve.

Creating a vector with coordinates of data points.

Creating a vector with light intensity from data.


Formatting plots6

Creating text.

FORMATTING PLOTS

EXAMPLE OF A FORMATTED PLOT

Formatting of the light intensity plot (cont.)

xlabel('DISTANCE (cm)')

ylabel('INTENSITY (lux)')

title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)

axis([8 24 0 1200])

text(14,700,'Comparison between theory and experiment.','EdgeColor','r','LineWidth',2)

legend('Theory','Experiment',0)

Labels for the axes.

Title for the plot.

Setting limits of the axes.

Creating a legend.

The plot that is obtained is shown again in the next slide.


Formatting plots7

FORMATTING PLOTS

EXAMPLE OF A FORMATTED PLOT


Formatting plots8

Use Figure, Axes, and Current Object-Properties in the Edit menu

FORMATTING PLOTS

FORMATTING A PLOT IN THE FIGURE WINDOW

Once a figure window is open, the figure can be formatted interactively.

Use the insert menu to

Click here to start the plot edit mode.


More formatting

More Formatting

Formatting the text in the , xlabel, ylabel, title, text and legend commands:

The modifiers are characters that are inserted within the string. Some of the modifiers that can be added are:


More formatting1

More Formatting

Greek characters:


More formatting2

More Formatting

Formatting the text in the , xlabel, ylabel, title, text and legend commands:


More formatting3

More Formatting


More formatting example1

More Formatting-Example1


More formatting example2

More Formatting-Example2

clc

xl=linspace(0,2*pi,10);

x2=linspace(0,2*pi,50);

x3=linspace(pi,2*pi,100);

x4=linspace(pi/3,2*pi,150);

yl=sin(xl);

y2=cos(x2);

y3=abs(sin(x3));

y4=sin(x4) .*sin(x4);

plot(xl,yl,'gs', x2,y2,'kp:', x3,y3, x4,y4,'r--');

legend('sin(x)', 'cos(x)', 'abs(sin(x»', '(sin(x)*sin(x)',3)

xlabel('\bfx - Radians','fontsize',14);

title('\itVarious Trigonometric Functions','fontname','arial','fontsize',20);

grid on


More formatting example2 cont

More Formatting-Example2-cont.


Plot color

Plot Color

To change the color of the plot, we use the WHITEBG command. This command typically toggles between a white background and a black one.

clc

xl=linspace(0,2*pi,10);

x2=linspace(0,2*pi,50);

x3=linspace(pi,2*pi,100);

x4=linspace(pi/3,2*pi,150);

yl=sin(xl);

y2=cos(x2);

y3=abs(sin(x3));

y4=sin(x4) .*sin(x4);

plot(xl,yl,'gs', x2,y2,'kp:', x3,y3, x4,y4,'r--');

legend('sin(x)', 'cos(x)', 'abs(sin(x»', '(sin(x)*sin(x)',3)

xlabel('x - Radians');

title('Various Trigonometric Functions');

WHITEBG


Plot color1

Plot Color

Without WHITEBG command


Plot color2

Plot Color

With the WHITEBG command


Plot color3

Plot Color

With the WHITEBG(‘m’) command


Plotting grid

Plotting Grid

  • The MATLABGRID command places a grid on the current plot. The command can be used in three forms:

    • GRID ON-Places a grid on the current plot.

    • GRID OFF-Removes the grid from the current plot.

    • GRID-Toggles the grid on or off.

clc

xl=linspace(0,2*pi,10);

x2=linspace(0,2*pi,50);

x3=linspace(pi,2*pi,100);

x4=linspace(pi/3,2*pi,150);

yl=sin(xl);

y2=cos(x2);

y3=abs(sin(x3));

y4=sin(x4) .*sin(x4);

plot(xl,yl,'gs', x2,y2,'kp:', x3,y3, x4,y4,'r--');

legend('sin(x)', 'cos(x)', 'abs(sin(x»', '(sin(x)*sin(x)',3)

xlabel('x - Radians');

title('Various Trigonometric Functions');

grid on


Plotting grid1

Plotting Grid


Obtaining numerical values from a plot

Obtaining Numerical Values from a Plot

Numerical values can be obtained from a plot using the GINPUT function. The syntax of the function is

[x, y] = ginput (N)

Where:

N is the number of points requested

x and y contain the x- and y-coordinates of the recorded points.

If N is omitted points are collected until you press the ENTER key.


Obtaining numerical values from a plot1

Obtaining Numerical Values from a Plot

clc

xl=linspace(0,2*pi,10);

x2=linspace(0,2*pi,50);

x3=linspace(pi,2*pi,100);

x4=linspace(pi/3,2*pi,150);

yl=sin(xl);

y2=cos(x2);

y3=abs(sin(x3));

y4=sin(x4) .*sin(x4);

plot(xl,yl,'gs', x2,y2,'kp:', x3,y3, x4,y4,'r--');

legend('sin(x)', 'cos(x)', 'abs(sin(x»', '(sin(x)*sin(x)',3)

xlabel('x - Radians');

title('Various Trigonometric Functions');

grid on

[x2,y2]=ginput(1);


Obtaining numerical values from a plot2

Obtaining Numerical Values from a Plot


Plots with logarithmic axes

PLOTS WITH LOGARITHMIC AXES

clc

omega=logspace(1,4,200);

mag=20*log10(abs(1000./(i*omega+1000)));

semilogx(omega, mag);

grid on;

ylabel('Gain(dB)');

xlabel('Frequency (rad/sec)');

title('Bode Magnitude plot of Vo/Vin');


Plots with logarithmic axes1

PLOTS WITH LOGARITHMIC AXES

semilogx(omega, mag)


Plots with logarithmic axes2

PLOTS WITH LOGARITHMIC AXES

semilogy(omega, mag)


Plots with logarithmic axes3

PLOTS WITH LOGARITHMIC AXES

loglog(omega, mag)


Subplots

Subplots

  • subplot(m,n,p) or subplot(mnp) : create a subplot in an array of axes

    >> subplot(2,3,1);

    >> subplot(2,3,4);

P=2

P=1

P=3

n

P=4

m


Subplots example

Subplots-Example

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

y = sin(x);

subplot(221), plot(x,y)

xlabel('x'),ylabel('sin 3 pi x')

subplot(222), plot(x,cos(3*pi*x))

xlabel('x'),ylabel('cos 3 pi x')

subplot(223), plot(x,sin(6*pi*x))

xlabel('x'),ylabel('sin 6 pi x')

subplot(224), plot(x,cos(6*pi*x))

xlabel('x'),ylabel('cos 6 pi x')


Subplots example1

Subplots-Example


Plots with special graphics

PLOTS WITH SPECIAL GRAPHICS

Vertical Bar plot bar(x,y)

clc

clear all

yr=1988:1994;

sl=[8 16 14 22 3 18 21];

bar(yr,sl,'r')

xlabel('YEAR')

ylabel('SALES-MILLION')


Plots with special graphics1

PLOTS WITH SPECIAL GRAPHICS

Horizontal Bar plot barh(x,y)

clc

clear all

yr=1988:1994;

sl=[8 16 14 22 3 18 21];

barh(yr,sl,'r')

xlabel('YEAR')

ylabel('SALES-MILLION')


Plots with special graphics2

PLOTS WITH SPECIAL GRAPHICS

Stairs plot stairs(x,y)

clc

clear all

yr=1988:1994;

sl=[8 16 14 22 3 18 21];

stairs(yr,sl,'r')

xlabel('YEAR')

ylabel('SALES-MILLION')


Plots with special graphics3

PLOTS WITH SPECIAL GRAPHICS

Stem plot stem(x,y)

clc

clear all

yr=1988:1994;

sl=[8 16 14 22 3 18 21];

stem(yr,sl,'r')

xlabel('YEAR')

ylabel('SALES-MILLION')


Plots with special graphics4

PLOTS WITH SPECIAL GRAPHICS

Pie plot pie(x)

clc

clear all

grade=[11 18 5 9 26]

pie(grade)

title('Class Grades')


Plots with special graphics5

PLOTS WITH SPECIAL GRAPHICS

AREA

clc

clear all

z=-pi:pi/5:pi;

area([sin(z);cos(z)]), title ('Figure2')


Plots with special graphics6

PLOTS WITH SPECIAL GRAPHICS

POLAR

clc

clear all

t= linspace(0,2*pi);

r=sin(2*t).*cos(2*t);

polar(t,r)


Plots with special graphics7

PLOTS WITH SPECIAL GRAPHICS

3D GRAPHS: Mesh and Surface PlotsExample – Graphing the sinc Function

clc

clear all

[X,Y] = meshgrid(-8:.5:8);

R = sqrt(X.^2 + Y.^2) + eps;

Z = sin(R)./R;

mesh(X,Y,Z,'EdgeColor','black')


Plots with special graphics8

PLOTS WITH SPECIAL GRAPHICS

3D GRAPHS: Mesh and Surface PlotsExample – Colored Surface Plots

clc

clear all

[X,Y] = meshgrid(-8:.5:8);

R = sqrt(X.^2 + Y.^2) + eps;

Z = sin(R)./R;

surf(X,Y,Z)

colormap hsv

colorbar


Plots with special graphics9

PLOTS WITH SPECIAL GRAPHICS

Add/edit text

zoom

Object select

Add arrow & line

3D rotate


Computer programming ecgd2102 using matlab

End of the Lecture

Let Learning Continue


  • Login