You are on page 1of 32

85

MATLAB has a powerful graphics system for presenting and visualizing data.
MATLAB directs graphics output to a window that is separate from the Command
Window. In MATLAB, this window is referred to as a figure. Graphics functions
automatically create new figure windows if none currently exist. If a figure window
already exists, MATLAB uses that window. If multiple figure windows exist, one is
designated as the current figure and is used by MATLAB as shown:

By default, MATLAB uses line style and color to distinguish the data sets plotted
in the graph. However, you can change the appearance of these graphic components
or add annotations to the graph to help explain your data for presentation.
The figure's default toolbar provides shortcuts to commonly used features. The
following picture shows the features available from this toolbar.

Note that you can enable two other toolbars from the View menu:

Mohammed Q. Ali
86

plot
It’s one of 2D plotting functions provided by MATLAB, plot function used to plot
points in a two-dimensional figure and connects them with straight line segments. If y
is a vector with n entries, then the function syntax is:
plot(y)
Plots the points
(1, y(1)), (2, y(2)), (3, y(3)),… , (n, y(n))
The plot is displayed in a separate window. For example:
>> y = [1 0 -1 3 4];
>> plot(y)
Yield the plot in Figure below:

If x is another vector with the same number of entries as y, then the function syntax:
plot(x,y)
Plots the points
(x(1),y(1)), (x(2), y(2)), (x(3), y(3)), … , (x(n), y(n))

And the commands:


>> x =[1 3 5 7 10];
>> y =[1 0 -1 3 4];
>> plot(x,y)

Mohammed Q. Ali
87

Produce the plot in Figure

Note : the 1st. argument of plot function is used to represent the horizontal axis and
2nd. argument is used to represent the vertical axis and the plot default color is blue.
Example 1: Plot the sinewave between the interval {-2π , 2π}
Sol:
To plot such kind of this wave its need to generate an appropriate number of
points to give the right shape of the wave, so using colon operator or linspace
function.

>> x=linspace(-2*pi,2*pi,20); % generates 20 points between (-2π , 2π)


>> plot(x,sin(x))

The plotting seems distorted, by increasing the number of points, the graph becomes
smoother.

Mohammed Q. Ali
88

>> x=linspace(-2*pi,2*pi); % generates 100 points between (-2π , 2π)


>> plot(x,sin(x))

Example 2: Plot the function y = −x3 +2x2 +4x−8, for x between −3 and 3 using dx =
0.1

Sol: where dx is the step value, and the commands are:

>> x = -3:0.1:3;
>> y = -x.^3+2*x.^2+4*x-8;
>> plot(x,y)

There are a variety of optional arguments for the plot function in MATLAB that
allow users to change colors, line style and linewidth also change the symbols
MATLAB uses as markers for the points being plotted. the function syntax is:

plot(X,Y,LineSpec,'PropertyName',PropertyValue)

Line specification defines line


Properties with their values specified
and marker type and its color
Line width, Marker size, Marker face
and edge coloring (for filled markers)

Mohammed Q. Ali
89

Line Specifiers (LineSpec) of line styles, color choices and markers that
MATLAB offers are listed in the tables below:

Line Style Specifier


Solid line (default) '-'
Dashed line '--'
Dotted line ':'
Dash-dot line '-.'

Color Specifier Color Specifier


White 'w' or 'white' Yellow 'y' or 'yellow'
Red 'r' or 'red' Cyan 'c' or 'cyan'
Green 'g' or 'green' Magenta 'm' or 'magenta'
Blue 'b' or 'blue' Black 'k' or 'black'

Marker Type Specifier Marker Type Specifier


Point (default) '.' Upward-pointing triangle '^'
Plus sign '+' Downward-pointing triangle 'v'
Circle 'o' Right-pointing triangle '>'
Asterisk '*' Left-pointing triangle '< '
Cross 'x' Five-pointed star (pentagram) 'p' or 'pentagram'
Square 's' or 'square' Six-pointed star (hexagram) 'h' or 'hexagram'
Diamond 'd' or 'diamond'

Note : the specifiers are added to the plot function as string regardless their order, for
example:
Command Description
plot(x, y) Plots a blue solid line without marker(default)
plot(x, y, 'g') Plots a green solid line without marker
plot(x ,y, ':r') Plots a red dotted line without marker
plot(x, y, 'o') Each point is marked with (blue *) without plotting line
plot(x, y, '*y') Each point is marked with (yellow *) without plotting line
plot(x, y, 's--k') Each point is marked with (square) and plots dashed line, their
colors are black

The property name is added to plot function as string followed by its property
value, the common properties are listed in a table below.

Property Name Description Property Value


LineWidth Specifies the width of line and marker boundary Greater than 0
MarkerSize Specifies the size of marker Greater than 0
MarkerEdgeColor Specifies the color of the marker boundary Must uses a color string
MarkerFaceColor Specifies the color of the filled marker Must uses a color string

Mohammed Q. Ali
90

For example:
>> plot(x,y,'-ro','LineWidth',2,'MarkerEdgeColor','k',...
'MarkerFaceColor','y','MarkerSize',6)

Plotting ( y = x2 ) a red solid line with points marked as circles. The line width is 2,
the markers boundaries have color black and filled with yellow and their size is 6.

Note : The line specifiers can also represented as property name followed by its
property value from specifiers tables which listed before.
Specifier Property Name Property Value
Line Style 'linestyle' A string specifies from table that mention before
Line color 'color' A string specifies from table that mention before
Marker 'marker' A string specifies from table that mention before

For example, plotting ( y = x2 ) using the line properties to get the same shape above.
>> plot(x,y,'linestyle','-','marker','o','color','r','LineWidth',2,...
'MarkerEdgeColor','k','MarkerFaceColor','y','MarkerSize',6)

There are additional basic plotting functions in MATLAB that allow users to plot
more than one graph in the same figure, insert a basic grid in the figure, name a figure,
etc. as shown in table.

Mohammed Q. Ali
91

Function Description Example


hold Freezes the current plot, so that an hold on
additional plot can be overlaid hold off
title Adds a title to a plot title('graph of y=x ∧2')
xlabel Adds a label to the x -axis Xlabel('The x values')
ylabel Adds a label to the y -axis Ylabel('y^2')
grid Adds a grid to the graph grid or grid on
grid off
pause Halts execution temporarily until press pause
any key or halt execution for n seconds pause(4)

Example 3: Suppose a set of time versus distance data were obtained through
Measurement. Write a script to Plot the table data

Time (sec) 0 2 4 6 8 10 12 14 16 18
Distance (ft) 0 0.33 4.13 6.29 6.85 11.19 13.19 13.96 16.33 18.17

Sol:
clear
x=0:2:18;
y=[0 0.33 4.13 6.29 6.85 11.19 13.19 13.96 16.33 18.17];
plot(x,y,'-or');
title('Laboratory Experiment 1')
xlabel('Time (sec)')
ylabel('Distance (ft)')
grid on

Mohammed Q. Ali
92

Example 4: Write a program to plot the trigometric functions {sinϴ and cosϴ} for
interval {-2π, 2π} by using 200 points
Sol:
clear
clf % clear current figure window
th=linspace(-2*pi,2*pi,200);
y1=sin(th);
y2=cos(th);
hold on
plot(th,y1); % plot sinewave
plot(th,y2) ; % plot cosine wave
title('Trigonometric Functions')
xlabel('The angle')

As it seems from figure, it is difficult to recognize which one is sinewave or cosine


wave. So it must using:
line colors or line style. The plot function rewrites as:
plot(th,y1); % plot sinewave
plot(th,y2,'r') % plot cosine wave with red color
OR
plot(th,y1); % plot sinewave
plot(th,y2,'--') % plot cosine wave with dashed line

multiple lines in same plot function. MATLAB interprets the input to plot as
alternating x and y vectors, as in
plot(X1,Y1,...,Xn,Yn)
Where the set of X1 and Y1 is the 1st plotting and so on. The plot function rewrites as:
plot(th,y1,th,y2); % plot sinϴ and cosϴ with different colors and same line specifiers

OR the plot function can written as:

plot(X1,Y1,LineSpec,...,Xn,Yn,LineSpec)

Plots lines defined by the Xn, Yn, LineSpec triplets. The plot command rewrites as:

Mohammed Q. Ali
93

plot(th,y1,'-ob',th,y2,':sr'); % plots sinϴ with blue solid line with circle marker
and cosϴ with dotted red line with square marker

IF the plot function is called with a single matrix argument, MATLAB draws a
separate line for each column of the matrix. The x -axis is labeled with the row index
vector, 1: k , where k is the number of rows in the matrix. For example
>> y = magic(3)
y =
8 1 6
3 5 7
4 9 2
Column 1
>> plot(y, '-s')

Column 3

Column 2

If plot function is called with two arguments, one a vector and the other a matrix
(at least one of the matrix dimensions = vector’s length), MATLAB successively

Mohammed Q. Ali
94

plots a line for each row (if the matrix’s column ≠ vector’s length) in the matrix, or
else plots a line for each column.
Example 5: write a program to plot a vector x=[1 3 7 9] with:
1) Square matrix
2) (5 X 4) matrix
3) (2 X 4) matrix
Labeled the axes, title and using grid.
Sol:
1) Generates (4X4) matrix (the length of vector = 4), and the program will be:
clc;clear;clf;
x=[1 3 7 9]
y=magic(4) % using magic matrix with (4 X 4)
plot(x,y,'-p ','linewidth',2);
grid;
title('Plotting Matrix vs Vector');
xlabel('Vector values');
ylabel('Matrix value');

Line for each column


of the matrix

2) Generates (5X4) matrix with integer random values and the program will be:
clc;clear;clf;
x=[1 3 7 9]
y=randi(15,5,4) % generates integer random
numbers range (1 - 15)
plot(x,y,'-s','linewidth',2);
grid;
title('Plotting Matrix vs Vector')
xlabel('Vector values')
ylabel('Matrix value')

Line for each row of


the matrix

Mohammed Q. Ali
95

3) Generates (2X4) matrix with integer random values. The program is:
clc;clear;clf;
x=[1 3 7 9]
y=randi(10,2,4) % generates integer random
numbers range (1 - 10)
plot(x,y,'-s','linewidth',2);
grid;
title('Plotting Matrix vs Vector')
xlabel('Vector values')
ylabel('Matrix value')

Line for each row of


the matrix

If both arguments of plot function are matrices. MATLAB plots line for each
column and the x-coordinates are taken from 1st matrix argument and the y-
coordinates are taken from 2nd matrix argument column by column. For example

>> x=[3 2 9;5 6 7;1 9 8]


x =
3 2 9
5 6 7
Column 1
1 9 8
>> y=[9 1 3;4 3 4;2 1 9]
y =
9 1 3
4 3 4
2 1 9
>> plot(x,y,'-o','linewidth',2);grid

Column 2 Column 3

axis
When the plot(x,y) function is executed, MATLAB creates axes with limits that are
based on the minimum and maximum values of the elements of x and y. The axis
function can be used to change the range of the axes. Here are some features of the
axis function:

Mohammed Q. Ali
96

axis Function Feature Description


axis([xmin ,xmax ,ymin ,ymax ]) Sets the limits for the x- and y-axis of
the current axes.
axis manual Freezes scaling for subsequent graphs
axis auto Returns to auto-scaling
axis square Sets the axes region to be square
axis equal Sets the same scale for both axes
axis off Turns off axis scaling and tic marks
axis on Turns on axis scaling and tic marks

Example 6: Write a script file to plot the function . where n is ranged


(1→5) and {-π ≤ ϴ ≤ π}. Uses the features of axis function to improve the plotting.

Sol: To distinguish among the axis function features in the program, so pause
function should be used at each feature:
clc;clf;clear;
x=linspace(-pi,pi); % Generate 100 points
for n=1:5;
y(:,n)=n*cos(x);
end
plot(x,y,'linewidth',2);
grid on;
pause
axis square;
pause
axis([-10 10 -10 10]);
pause
axis auto;
pause
axis equal;
pause
axis off
pause
axis on

Mohammed Q. Ali
97

legend
The legend command places a legend on the plot. The legend shows a sample of
the line type of each graph that is plotted, and places a label, specified by the user,
beside the line sample. The syntax is:

legend('string 1','string 2',...,position )

Where position is an optional number used to specify the legend location as shown:

Position Location
-1 Outside axes on right side
0 Inside axes (Best)
1 Upper right corner of axes (default)
2 Upper left corner of axes
3 Lower left corner of axes
4 Lower right corner of axes

Example 7: Write script to plot y=x3-1 and y=1-x3 in same figure whare x={-2,2} and
dx=0.1 using legend to define your plotting.

Sol:
clc;clear;clf;
x=-2:0.1:2;
y=x.^3-1;
y2=1-x.^3;
plot(x,y,x,y2,'linewidth',2);
legend('y= x^3-1','y= 1-x^3',2); % displays legend at upper left

Mohammed Q. Ali
98

Example 8: Write a script to plot with 20 point the functions y=xn where n (1→5)
and x={-1,1}. Using legend to define for each plotting line and its string should be as:
at the best location.

Sol: To display legend as shown in example its done by generating a string matrix
and each row of it defines a plotting line .

clc;clear;clf
x=linspace(-1,1,20); % Generates 20 points
for n=1:5
y(:,n)=x.^n;
end
plot(x,y,'linewidth',2);
st_matrix(1,:)='y=x '; % the legend string of y=x assign as 1st. row of string matrix
for n=2:4
st_matrix(n,:)=['y=x^' num2str(n)]; % generate other strings for other plotting lines
end
legend(st_matrix,0); % Displays the legend at best location Transform
Number to
String

text
A text label can be placed in the plot with the text or gtext function:

text(x,y,'text as string')
gtext('text as string')

Mohammed Q. Ali
99

The text function places the text in the figure such that the first character is
positioned at the point with the coordinates x,y (according to the axes of the figure).
The gtext command places the text at a position specified by the user (with the mouse).
From example 7 program, replace:

legend('y= x^3-1','y= 1-x^3',2);


With
text(0,-1.75,'y= x^3-1');
text(-0.35,2,'y= 1-x^3');

Or
gtext('y= x^3-1')
gtext('y= 1-x^3')

The texts in the ( xlabel, ylabel, title, legend and text )functions can be formatted
to customize the font, size, style (italic, bold, etc.), and color. Formatting can be done
by adding optional PropertyName and PropertyValue arguments following the string
inside the function. For example:
text(x,y,'text as string','PropertyName',PropertyValue)

PropertyName Description Example


the orientation of the text
Rotation (in degree)
text(0.5,0.5,'y=1/x','Rotation',30)
the size of the font (in
FontSize points)
title('The Sinewave','fontsize',20)
the weight of the characters
FontWeight (light, normal, bold) ylabel('Popularity','fontweight','b')
The type of font (Arial, title('The 3D Surface' , 'FontName' ,
FontName Calibri, etc.) 'Comic Sans MS')

The text slope (Normal, xlabel('The angle','fontAngle' ,'i')


FontAngle Italic, oblique)
The color of the text (e.g., gtext('Hello World','Color','y')
Color r, b, etc.)
The color of the rectangle gtext('y=sin(x)','BackgroundColor','g')
BackgroundColor that encloses the text
Specifies the color of a box title('The Ellipse','EdgeColor','r')
EdgeColor drawn around the text
specify the width of the title('The Ellipse' , 'Edgecolor' , 'r' ,
LineWidth rectangle edge (in points) 'LineWidth', 5)

Mohammed Q. Ali
100

Notes:
Its can used more than one property name in a MATLAB command.
The color property not only used with basic color (red, green, … ), but can used
with RGB color model and the syntax of color property is:
'Color',[r g b]

Where [r g b] is red, green and blue components, their values range between 0 to 1.
For examples:

Color White Black Red Green Blue Yellow Magenta Teal


[r g b] [1 1 1] [0 0 0] [1 0 0] [0 1 0] [0 0 1] [1 1 0] [1 0 1] [0 0.5 0.5]

A single character can be displayed as a subscript or a superscript by typing _


(the underscore character) or ^ in front of the character, respectively. A long
superscript or subscript can be typed inside { } following the _ or the ^. For
examples:

Text MATLAB
H2O + H2SO4 'H_2O + H_2SO_4'
r2 = x 2 + y 2 'r^2 = x^2 + y^2'
'c_{ij}=(a_{ij})^{b_{ij}}'

Some formatting can also be done by adding modifiers inside the string. Such
as:

\bf — Bold font


\it — Italic font
\rm — Normal font
\fontname{fontname} — Specify the name of the font family to use.
\fontsize{fontsize} — Specify the font size in points
\color[rgb]{r g b}|{color} — Specify color for succeeding characters

For Examples:

Text MATLAB
The Spline Curve '\fontname {Jokerman} \it The spline curve'
The Spline Curve '\color[rgb]{0.8 0.6 0.2} \fontsize {20} \fontname {Calibri}
\bf The spline curve'

Greek characters and mathematical symbols can be included in the text by


typing \ (back slash) before the name of the letter:

Mohammed Q. Ali
101

MATLAB Symbol MATLAB Symbol MATLAB Symbol MATLAB Symbol


\alpha α \mu µ \angle ∠ \geq
\beta β \tau τ \cap ∪ \in ∈
\epsilon ε \rho ρ \supset ⊃ \infty ∞
\gamma γ \Gamma Γ \int \leftarrow ←
\omega ω \Omega Ω \div \rightarrow →
\phi φ \Phi Φ \surd √ \neq
\theta θ \Theta Θ \cup ∩ \0 ∅
\sigma σ \Sigma Σ \subseteq ⊆ \supseteq ⊇
\pi π \Pi Π \leq ! \subset ⊂

For examples:

Text MATLAB
← sin&'( ' \leftarrow sin(\pi)'
) *+, -./&01( 2 3/34&01( '\ite^{i\omega\tau}=cos(\omega\tau)+i sin(\omega\tau)'

Example 9: write a program to plot the graphic below with dx=0.05, where:
1) the font size for title is 16 and its name is georgia
2) the other fonts of graphic are arial and their size 14
3) all the used fonts are bolt

Mohammed Q. Ali
102

Sol:
clc;clear;clf;
X=0:0.05:2;
for n=3:8
Y(:,n-2)=X.^(1/n);
st(n-2,:)= ['^' num2str(n) '\surd']
end
plot(X,Y,'linewidth',2);
legend(st,4);
title('^n\surd','fontname','georgia','fontsize',16,'fontweight','b');
xlabel('\bf\fontname{arial}\fontsize{14}X');
ylabel('\bf\fontname{arial}\fontsize{14}\surd');
grid on

fplot ezplot
MATLAB has some built-in functions. One built-in function is fplot, which plots a
function between limits that are specified. The syntax of the function is:

fplot(fnhandle, [xmin xmax],Linespec)

For example, to pass the sin function to fplot one would pass its handle:
>> fplot(@sin, [-pi pi])
Or the argument of the fplot function writes in other way:

>> fplot('sin(x)',[-pi pi])

The fplot function is a nice shortcut, it is not necessary to create x and y vectors, and
it plots a continuous curve rather than discrete points.

Example 10: Write a script to plot functions & 5 6, 8 9 , 6: ; <6 2 =( where 6 ∈


>?, :@. Using fplot function

Sol:
clc;clf;clear;
hold on
fplot(@log,[0 2]);
fplot(@tanh,[0 2],':r');
fplot('x.^2-3*x+1',[0 2],'--g');

Mohammed Q. Ali
103

For an implicit equation f(x,y) = 0, the relationship between x and y cannot be


explicitly formulated. Thus the conventional plot function cannot be used. The
MATLAB function ezplot can be used to draw the implicit function curve. The syntax
of function

ezplot(implicit function,[min max])

For example, Draw the curve of the implicit function:


f(x,y) = x2 sin(x + y2 ) + 5cos(x2 + y) = 0
From the given function, it can be seen that the analytical explicit solution of x-y
relationship cannot be found. Thus the plot function cannot be used, so the solution is:
>> ezplot('x^2 *sin(x+y^2)+5*cos(x^2+y)')

Another function that is very useful with any type of plot is subplot, which creates
a matrix of plots in the current Figure Window. The syntax of subplot function is:
subplot(m,n,p);
by dividing the figure window into m×n small sets of axes, p chooses which location
in the window the plot should go to. The order is from left to right, top to bottom.
For example:
subplot(3,2,1), text(0.5,0.5,'1', 'FontSize',20)
subplot(3,2,2), text(0.5,0.5,'2', 'FontSize',20)
subplot(3,2,3), text(0.5,0.5,'3', 'FontSize',20)
subplot(3,2,4), text(0.5,0.5,'4', 'FontSize',20)
subplot(3,2,5), text(0.5,0.5,'5', 'FontSize',20)
subplot(3,2,6), text(0.5,0.5,'6', 'FontSize',20)

Mohammed Q. Ali
104

Example 11: write a script to plot f(x)=x4-2x3-5x2+3x-7 and their derivatives


to 3rd. derivate in same figure window. Format your plotting by using grid

Sol:
clc;clear;
syms x;
fx=x^4-2*x*3-5*x^2+3*x-7;
subplot(2,2,1);
ezplot(fx);
grid on;
subplot(2,2,2);
ezplot(diff(fx));
grid on;
subplot(2,2,3);
ezplot(diff(fx,2));
grid on;
subplot(2,2,4);
ezplot(diff(fx,3));
grid on;

Mohammed Q. Ali
105

MATLAB uses what it calls Handle Graphics in all its figures. All figures consist
of different objects, each of which is assigned a handle. The object handle is a unique
real number that is used to refer to the object. The various plot functions return a handle
for the plot object, which can then be stored in a variable. For example, the plot of a
sin function returns a real number, which is the object handle. This handle will remain
valid as long as the object exists.

>> x=linspace(-pi,pi);
>> y=sin(x);
>> h1=plot(x,y)
h1 =
174.0016
After getting the plot, the Figure Window should not be closed, as that would make
the object handle invalid since the object wouldn’t exist anymore! The properties of
that object can be displayed using the get function. This shows properties such as
(Color, LineStyle, LineWidth, and so on).

>> get(h1)
DisplayName: ''
Annotation: [1x1 hg.Annotation]
Color: [0 0 1]
LineStyle: '-'
LineWidth: 0.5000
Marker: 'none'
MarkerSize: 6
MarkerEdgeColor: 'auto'
MarkerFaceColor: 'none'
XData: [1x100 double]
YData: [1x100 double]
ZData: [1x0 double]
BeingDeleted: 'off'
ButtonDownFcn: []
Children: [0x1 double]
Clipping: 'on'
CreateFcn: []
DeleteFcn: []
BusyAction: 'queue'
HandleVisibility: 'on'
HitTest: 'on'
Interruptible: 'on'
Selected: 'off'
SelectionHighlight: 'on'
Tag: ''
Type: 'line'
UIContextMenu: []

Mohammed Q. Ali
106

UserData: []
Visible: 'on'
Parent: 173.0033
XDataMode: 'manual'
XDataSource: ''
YDataSource: ''
ZDataSource: ''

A particular property can also be displayed, for example, to see the line width or color:
>> get(h1,'lineWidth')
ans =
0.5000
>> get(h1,'Color')
ans =
0 0 1
All the properties listed by get can be changed, using the set function. The syntax
of function is:
set(objhandle, 'PropertyName', property value)
For example, to change the line width from the default of 0.5 to 1.5:
>> set(hl,'LineWidth',1.5)
As long as the Figure Window is still open and this object handle is still valid, the
width of the line will be increased. The properties can also be set in the original
function call. For example, this will increase the line width.
>> hl = plot(x,y, 'LineWidth', 2.5);

The 2D geometric shapes including triangles, quadrilaterals, polygons and 2D


curved shape such as circle, ellipse and so on. MATLAB provides built-in functions
and many way to draw these shapes.
The coordinates of the vertices are needed to plot n-sides shapes. The x and y
coordinates of shape’s vertices are represented as arguments vectors of plot function.
For example, plot shapes below

Mohammed Q. Ali
107

In order to plot a shape, it must arrange vertices respectively and repeat the 1st
vertex as last vertex to have closed shape so n vertices must be entered as (n+1)
vertices. For fig -1-, the coordinate vectors will be:
x1=[1 3 6 1]; % repeats the 1st vertex x-coordinate
y1=[4 1 6 4]; % repeats the 1st vertex y-coordinate
plot(x1,y1,'linewidth',2)
For fig -2-, the coordinate vectors will be:
x2=[0 2 5 3 0];
y2=[4 0 2 7 4];
plot(x2,y2,'linewidth',2)
For fig -3-, the coordinate vectors will be:
x3=[3 10 10 6 0 3];
y3=[3 3 8 12 6 3];
plot(x3,y3,'linewidth',2)
for fig -4-, with based on the side length of square shape it’s easy to calculate the other
vertices coordinates:
x4=[5 5 2 2 5];
y4=[4 7 7 4 4];
plot(x4,y4,'linewidth',2)

fill
MATLAB provides a function called fill to plot and fill 2D-ploygons with specific
color, the syntax of the function is:
fill(x,y, ColorSpec)

Where x and y are the n-vertex coordinates and ColorSpec is the filled color
specifier.

Example 12: Write a script to draw and fill with different colors the shapes in figures
above using sub-figure for each shape, formats the axis figure to square.

Sol:
x1=[1 3 6];
y1=[4 1 6];
subplot(2,2,1);

Mohammed Q. Ali
108

fill(x1,y1,'r');
axis equal;
x2=[0 2 5 3];
y2=[4 0 2 7];
subplot(2,2,2);
fill(x2,y2,'white');
axis equal;
x3=[3 10 10 6 0];
y3=[3 3 8 12 6];
subplot(2,2,3);
fill(x3,y3,'b');
axis equal;
x4=[5 5 2 2];
y4=[4 7 7 4];
subplot(2,2,4);
fill(x4,y4,'g');
axis equal;

Example 13: Write a program to plot n-sides regular ploygon and fill it with random
color,the running of program ends or not when the user answer the sentence:
Do you want exit program? (y or n):
Sol:
check='n'
while check=='n'
clc;clear;
N=input('Enter The no. polygon sides(n>2) :');
R=input('Enter The Radius :');
th=[0:1/N:1]*360;
X=R*cosd(th);
Y=R*sind(th);
fill(X,Y,[rand,rand,rand]);
hold on; axis square;
title(['The ' num2str(N) '-sides polygon']);
disp('-----------------------------------');
check=input('Do you want exit? (y or n): ','s');
disp('-----------------------------------');
if check=='y'
close; % closes the figure window
break;
end
clf;
end

Mohammed Q. Ali
109

rectangle
The rectangle function used to draw a 2D-rectangle and the syntax of function is:
rectangle('Position',[x,y,w,h])

Where x,y is the point’s coordinates which rectangle draw from it with width w and
height h, for example:
>> rectangle('position',[2,3,5,5])% draw rectangle from point(2,3) with width 5 and height 5

It can also draw the rectangle using the values for the property name/property value
pairs such as LineStyle, LineWidth, EdgeColor, FaceColor and so on.
Example 13: plot two rectangles:
1) The 1st started point(1,3) and dimentions (7x4) and its properties are: The
line width=2 , line color=blue, fill color=green, line style=dashed
2) The 2nd started point(3,3) and dimentions (4x4) and its properties are: The
line width=1.5 , line color=red, fill color=cyan
Using x-axis and y-axis limits (0-10) and they are equals.

Sol:
clc;clf
rectangle('position',[1,3,7,4],'linewidth',2,'linestyle','--',...
'edgecolor','blue','facecolor','green');
rectangle('position',[3,3,4,4],'linewidth',1.5,...
'edgecolor','r','facecolor','c');
axis([0 10 0 10]);
axis equal;

The curvature property of the function is used to vary from rectangle to ellipse and
the syntax is:
rectangle('Curvature',[x,y])

Mohammed Q. Ali
110

Where x and y are values range (0 → 1), x is the fraction of width of the rectangle
that is curved along the top and bottom edges and y is the fraction of the height of the
rectangle that is curved along the left and right edges. From example before the
rectangle function statements will be:
rectangle('position',[1,3,7,4],'curvature',[1 1],'linewidth',2,...
'linestyle','--','edgecolor','blue','facecolor','green');
rectangle('position',[3,3,4,4],'curvature',[0.8 0.5],...
'linewidth',1.5,'edgecolor','r','facecolor','c');

• The circle is ploted in different ways base on its equation: x2+y2=r2 or on


(r,θ) where: X=Rcos(θ) and Y=Rsin(θ) 0 ≤ θ ≤ 2π :
Example 14: Write a scrite to plot a circle in different ways using sub-figure for each
plot. Add title and square the axis.
Sol:
clc;clear;
subplot(2,2,1);
C=ezplot('x^2+y^2=25');
set(C,'linecolor','b','linewidth',2);
axis equal;
subplot(2,2,2)
x=[-5:0.1:5];
y=[sqrt(5^2-x.^2) ; -sqrt(5^2-x.^2)];
plot(x,y,'linewidth',2);
title('y= \pm \surd {R^2- x^2}');
axis equal;
subplot(2,2,[3 4])
for th=1:360
x=5*cosd(th);y=5*sind(th);
hold on;

Mohammed Q. Ali
111

plot(x,y);
end
title('(Rcos\theta , Rsin\theta)');
axis equal;

The equation for an ellipse is:


AB EB
2 1
CDB CFB
But its parametric form is:
A CD cos J K4L E CF sin J MN)C) 0 ! J ! 2'

Example 15: write a function to plot a filled ellipse with random color, where its
arguments are the rx and ry . Add a figure title and find approperate axis limits and
equilized them.
Sol:
function P = ellipse(rx,ry)
% plot a filled ellipse with random color
clf;
hold on;
for th=1:360
x(th)=rx*cosd(th);
y(th)=ry*sind(th);
plot(x,y);
end
P=fill(x,y,[rand,rand,rand]);
axis([-rx rx -ry ry]);
axis equal;
title(['Plotting Ellipse with Rx=' num2str(rx) ' and Ry=' num2str(ry)])

Mohammed Q. Ali
112

if ~nargout % the no. of output arguments nargout it’s used to handle error of
clear P calling the function w/o output
end
end

Example 16: write a function plot_arc to draw arc and its pie with random color.
Which the function arguments are: [ start and end of arc(in degrees),the center point
of arc and the radius in x and y-axis]. Using axis properties.
Sol:
function P = plot_arc(a,b,xc,yc,Rx,Ry)
% Plot an arc and a pie with random color.
% a is start of arc in degrees,
% b is end of arc in radians,
% (xc,yc) is the center of the arc.
% Rx is the radius in x-axis.
% Ry is the radius in y-axis.
Clf;
t = linspace(a,b);
x = Rx*cosd(t) + xc;
y = Ry*sind(t) + yc;
plot(x,y,'linewidt',3);
axis([xc-Rx-1 xc+Rx+1 yc-Ry-1 yc+Ry+1])
axis equal;
hold on
pause
x = [x xc];
y = [y yc];
P =fill(x,y,[rand,rand,rand]);
if ~nargout
clear P
end
end
>> plot_arc(30,175,9,4,5,7)

Mohammed Q. Ali
113

There are more ways to display data. MATLAB has a number of functions designed
for plotting specialized 2D graphs such as:
area
This function fills the area beneath curve and its syntax is:

area(x,y,'PropertyName',PropertyValue,...)

Where x and y are vectors and the filled area is between 0 to y, PropertyName/
PropertyValue pairs for the patch graphics object created by area.

Example 17: Plot the equation y=3x3-4x+2 for -5 ≤ x ≤ 5 and fill the area
function for -4 ≤ x ≤ 1

Sol:
clc;clear;clf;
x=linspace(-5,5);
y=@(x) 3*x.^3-4*x+2;
xa=x(x>=-4 & x<=1);
hold on;
axis([min(x) max(x) min(y(x)) max(y(x))]);
fplot(y,[-5 5]);
title('\it\fontsize{16} y=3x^3-4x+2')
area(xa,y(xa),'BaseValue',min(y(x)),'FaceColor','g');

bar
This function displays the values in a vector or matrix as vertical or horizontal bars.
The function syntax is:
bar(x,Y) or barh(x,Y)

Where x is a vector defining the x-axis intervals for the vertical bars and x values
cannot be duplicated. If Y is a matrix, bar groups the elements of each row in Y at
corresponding locations in x.

Example 17: write a script to plot the data of car sales using bar function and its
properties with sub-figure for each shape. (improve your plotting)

Sales (units) 11233 16821 29624 26566 10395 5412 4029 8946 17210
Year 2005 2006 2007 2008 2009 2010 2011 2012 2013

Mohammed Q. Ali
114

Sol:
clc;clf;clear;
sales=[11233 16821 29624 26566 10395 5412 4029 8946 17210];
year=2005:2013;
subplot(2,2,1)
bar(year,sales,'red') % red vertical bars
xlabel('Years');ylabel('Car Units');
title('Car Sales');
subplot(2,2,2)
barh(year,sales,'yellow') % yellow horizontal bars
ylabel('Years');xlabel('Car Units');
title('Car Sales');
subplot(2,2,[3 4])
bar(year,sales,1) % vertical bars with width=1
xlabel('Years');ylabel('Car Units');
title('Car Sales');

pie
Pie charts are useful for visualizing the relative sizes of different but related quantities.
The function syntax is:
pie(x)

Where x is the data vector to be plotted

Mohammed Q. Ali
115

For example, the table below shows the area of the Continents of the world

Continent Asia Africa Europe N. America S. America Oceania Antarctica


Area
43.8 31.4 10.2 24.5 17.8 9 13.7
(million km2)

Sol:
clc;clear
Continent={'Asia','Africa','Europe','N. America','S.
America','Oceania','Antarctica'};
area=[43.8 31.4 10.2 24.5 17.8 9 13.7];
pie(area)
legend(Continent,-1)

Polar coordinates, in which the position of a point in a plane is defined by the angle
θ and the radius (distance) to the point, are frequently used in the solution of science
and engineering problems. The polar function is used to plot functions in polar
coordinates. The function syntex is:

polar(theta,radius,’line specifiers’)

where theta and radius are vectors whose elements define the coordinates of the
points to be plotted and The line specifiers are the same as in the plot
command.
The polar function plots the points and draws the polar grid. To plot a function C
Q&J( in a certain domain, a vector for values of θ is created first, and then a vector r
with the corresponding values of is created using element-by- element calculations.
The two vectors are then used in the polar command.

Mohammed Q. Ali
116

:
For example, a plot of the function R < S: T 2 for ? ! ! :U is shown
below.

Sol:
Clc;clear;
th=linspace(0,2*pi,200);
r=3*cos(0.5*th).^2+th;
polar(th,r);

Example 18: Write a script file to plot (uses 500 points) V&8( W|YZ[&\8(| V R ? !
8 ! :U with red dashed line and line width=2 using polar coordinates.

Sol:
clc;clear
N=input('the Value of N : ');
t = linspace(0,2*pi,500);
r = sqrt(abs(sin(N*t)));
p=polar(t,r,'--r');
set(p,'linewidth',2)

Mohammed Q. Ali

You might also like