Vous êtes sur la page 1sur 35

Basic of MATLAB

Lecture 4

1
Graphics

A graph is a collection of points, in 2,3 or even 4


dimensions, that may or may not be connected by lines
or polygons.
Most math software packages hide this from the user by
sampling a continuous function to generate the points.
Matlab is designed to work with matrices, rather than
functions.
Matrices are a convenient way to store a collection of
numbers - which is exactly what is needed when
graphing.
Thus all graphing commands in Matlab accept matrices
as their argument, rather than a function.

2
Graphics

On the other hand, Matlab's approach makes it very


easy to visualize data and to create graphics based on
lists of points.
Another unique feature of Matlab's graphics engine is
the way in which it displays graphical output.
In Matlab, there is (usually) only one plotting window.
Subsequent plotting commands will add to the old plot,
unless you request a new one be made.
This allows a plot to be made, then adjusted later to suit
your needs.

3
EXAMPLE OF A 2-D PLOT
Plot title Legend
Light Intensity as a Function of Distance
1200
Theory
y axis Experiment

label 1000

Text
Tick-mark
800
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
4
2D plot() COMMAND

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.
The plot command creates a single curve with the x
values on (horizontal axis) and the y values on the
ordinate (vertical axis).
The MATLAB command to plot a graph is plot(x,y). The
vectors x= (1;2;3;4;5;6) and y= (3;1;2;4;5;1) produce the
picture shown in next slide.
5
Basic Plotting

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

>> plot(x,y)
4

-1
1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

6
Basic Plotting

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 you specify two vectors as arguments, plot(x,y)
produces a graph of y versus x.
For example, these statements use the colon operator to
create a vector of x values ranging from zero to ,
compute the sine of these values, and plot the result.

7
Basic Plotting

>>x = 0:pi/100:2*pi;
>>y = sin(x);
1
>>plot(x,y) 0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

8
Specifying Line Styles and
Colors

It is possible to specify color, line styles, and


markers (such as plus signs or circles) when you
plot your data using the plot command:
plot(x,y,'color_style_marker ')
color_style_marker is a string containing from one
to four characters (enclosed in single quotation
marks) constructed from a color, a line style, and
a marker type.

9
Specifying Line Styles and
Colors

Where color_style_marker is a triplet of values from the


following table
To additional information, type help plot or doc plot.

10
Specifying Line Styles and
Colors

If you specify a marker type but not a line style, MATLAB


draws only the marker. For example, plot(x,y,'ks') plots
black squares at each data point, but does not connect
the markers with a line.
The statement plot(x,y,'r:+') plots a red dotted line and
places plus sign markers at each data point.
You may want to use fewer data points to plot the
markers than you use to plot the lines.
This following example plots the data twice using a
different number of points for the dotted line and marker
plots.

11
Specifying Line Styles and
Colors
>> x1 = 0:pi/100:2*pi;
>>x2 = 0:pi/10:2*pi;
>>plot(x1,sin(x1),'r:',x2,sin(x2),'r+')
1

0.8

0.6

0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

12
FORMATTING PLOTS
There are two methods to format a plot:

1. 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.

2. 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.

13
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.

14
FORMATTING COMMANDS

legend(string1,string2,string3)
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.

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.

15
FORMATTING COMMANDS

MATLAB enables you to add axis labels and titles. For example,
using the graph from the previous example,
Now label the axes and add a title. The character \pi creates the
symbol . Plot of the Sine
1
>> xlabel('x = 0:2\pi')
0.8
>> ylabel('Sine of x')
0.6
>> title('Plot of the Sine')
0.4

0.2
Sine of x

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7
x = 0:2

16
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]; Creating vector x for plotting the theoretical curve.

y=95000./x.^2; Creating vector y for plotting the theoretical curve.

xd=[10:2:22]; Creating a vector with coordinates of data points.

yd=[950 640 460 340 250 180 140]; Creating a vector with
light intensity from data.
plot(x,y,'-','LineWidth',1.0)
hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)
hold off

17
EXAMPLE OF A FORMATTED
PLOT
Formatting of the light intensity plot (cont.)

xlabel('DISTANCE (cm)') Labels for the axes.

ylabel('INTENSITY (lux)') Title for the plot.


title('\fontname{Arial}Light Intensity as a Function of
Distance','FontSize',14)
axis([8 24 0 1200]) Setting limits of the axes.

text(14,700,'Comparison between theory and


Creating text.
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0) Creating a legend.

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

18
EXAMPLE OF A FORMATTED
PLOT

19
FORMATTING A PLOT IN THE
FIGURE WINDOW
Once a figure window is open, the figure can be formatted interactively.
Use the insert menu to

Use Figure, Click here to start the


Axes, and plot edit mode.
Current
Object-
Properties in
the Edit menu

20
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.

21
THE fplot COMMAND

A plot of: y x 2 4 sin(2 x) 1 for 3 x 3

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

22
PLOT MULTIPLE GRAPHS IN
THE SAME PLOT

Multiple x-y pair arguments create multiple graphs with a


single call to plot.
MATLAB automatically cycles through a predefined (but
user settable) list of colors to allow discrimination
between each set of data.
For example, these statements plot three related
functions of x, each curve in a separate distinguishing
color.
The legend command provides an easy way to identify
the individual plots.

23
PLOT MULTIPLE GRAPHS IN
THE SAME PLOT
>>y2 = sin(x-.25);
>>y3 = sin(x-.5); 1

>>plot(x,y,x,y2,x,y3) 0.8
sin(x)
sin(x-.25)
sin(x-.5)
>>legend('sin(x)', 0.6

'sin(x-.25)','sin(x-.5)') 0.4

0.2

-0.2

-0.4

-0.6

-0.8

-1
0 1 2 3 4 5 6 7

24
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:)

25
PLOT MULTIPLE GRAPHS IN
THE SAME PLOT
Plot of the function, y 3x 3 26 x 10 and its first and
second derivatives, for 2 x 4 , all in the same plot.

x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
2 x 4
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

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.

26
PLOT MULTIPLE GRAPHS IN
THE SAME PLOT

120

100

80

60

40

20

-20

-40
-2 -1 0 1 2 3 4

27
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.

28
PLOT MULTIPLE GRAPHS IN
THE SAME PLOT
Plot of the function, y 3 x 3
26 x 10 and its first and
second derivatives, for 2 x 4 all 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

29
Figure Windows

Graphing functions automatically open a new figure window if there


are no figure windows already on the screen.
If a figure window exists, MATLAB uses that window for graphics
output.
If there are multiple figure windows open, MATLAB targets the one
that is designated the current figure (the last figure used or clicked
in).
To make an existing figure window the current figure, you can click
the mouse while the pointer is in that window or you can type
figure(n) where n is the number in the figure title bar.
The results of subsequent graphics commands are displayed in this
window.
To open a new figure window and make it the current figure, type
figure
>>plot(x,y)
>>figure , plot(x,y1)
30
Multiple Plots in One Figure

The subplot command enables you to display multiple


plots in the same window or print them on the same
piece of paper.
Typing subplot(m,n,p) partitions the figure window into
an m-by- n matrix of small subplots and selects the pth
subplot for the current plot.
The plots are numbered along first the top row of the
figure window, then the second row, and so on.
For example, these statements plot data in four different
subregions of the figure window.

31
Multiple Plots in One Figure

>>x = 0:pi/100:2*pi;
>> y=sin(x);
>> y1=sin(2*x);
>> y2=cos(x);
>> y3=cos(2*x);
>> subplot(2,2,1);plot(x,y,'b*')
>> subplot(2,2,2);plot(x,y1,'k:+')
>> subplot(2,2,3);plot(x,y2,'r--')
>> subplot(2,2,4);plot(x,y2,'c-.s')

32
Multiple Plots in One Figure

33
Basic 3-D Graphics

34
Exercise

Create a 1x41 matrix x that counts from -10 to 10, and a


1x41 matrix y made by squaring the entries of the first
matrix.
Plot the points. Each pair is plotted, so <x(1), y(1)> is a
point, <x(2), y(2)> is a point, etc.
Generate some new 1x11 matrices t from pi to 2pi with
step pi/5, and 1x11 matrix v by cos(t).
Create a new plot window, and plot the points with blue
stars at the data points and dotted lines for t and v.
Give the current plot a title cos(x) function.
Add x axis label ( x2 ).
Add y axis label (cos(x)).
35

Vous aimerez peut-être aussi