A Brief Introduction to Engineering Computation with MATLAB by Serhat Beyenir - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Chapter 3Graphics

3.1Plotting in MATLAB*

Plotting basics.

GraphingWithMATLAB

A picture is worth a thousand words, particularly visual representation of data in engineering is very useful. MATLAB has powerful graphics tools and there is a very helpful section devoted to graphics in MATLAB Help: Graphics. Students are encouraged to study that section; what follows is a brief summary of the main plotting features.

Two-Dimensional Plots

The plot Statement

Probably the most common method for creating a plot is by issuing plot(x, y) statement where function y is plotted against x.

Example 3.1

Type in the following statement at the MATLAB prompt:

x=[-pi:.1:pi]; y=sin(x); plot(x,y);

After we executed the statement above, a plot named Figure1 is generated:

Plot
Figure 3.1
Graph of sin(x)

Having variables assigned in the Workspace, x and y=sin(x) in our case, we can also select x and y, and right click on the selected variables. This opens a menu from which we choose plot(x,y). See the figure below.

PlotFromWorkspace
Figure 3.2
Creating a plot from Workspace.

Annotating Plots

Graphs without labels are incomplete and labeling elements such as plot title, labels for x and y axes, and legend should be included. Using up arrow, recall the statement above and add the annotation commands as shown below.

x=[-pi:.1:pi];y=sin(x);plot(x,y);title('Graph of y=sin(x)');xlabel('x');ylabel('sin(x)');grid on

Run the file and compare your result with the first one.

sinxLabels
Figure 3.3
Graph of sin(x) with Labels.

Type in the following at the MATLAB prompt and learn additional commands to annotate plots:

help gtext
help legend
help zlabel

Superimposed Plots

If you want to merge data from two graphs, rather than create a new graph from scratch, you can superimpose the two using a simple trick:

% This script generates sin(x) and cos(x) plot on the same graph
% initialize variables
x=[-pi:.1:pi];      %create a row vector from -pi to +pi with .1 increments
y0=sin(x);          %calculate sine value for each x
y1=cos(x);          %calculate cosine value for each x
% Plot sin(x) and cos(x) on the same graph
plot(x,y0,x,y1);
title('Graph of sin(x) and cos(x)'); %Title of graph
xlabel('x');                %Label of x axis
ylabel('sin(x), cos(x)');   %Label of y axis
legend('sin(x)','cos(x)');  %Insert legend in the same order as y0 and y1 calculated
grid on                     %Graph grid is turned

sinxLabelsLegend
Figure 3.4
Graph of sin(x) and cos(x) in the same plot with labels and legend.

Multiple Plots in a Figure

Multiple plots in a single figure can be generated with subplot in the Command Window. However, this time we will use the built-in Plot Tools. Before we initialize that tool set, let us create the necessary variables using the following script:

% This script generates sin(x) and cos(x) variables
clc                 %Clears command window
clear all           %Clears the variable space
close all           %Closes all figures
X1=[-2*pi:.1:2*pi];  %Creates a row vector from -2*pi to 2*pi with .1 increments
Y1=sin(X1);          %Calculates sine value for each x
Y2=cos(X1);          %Calculates cosine value for each x
Y3=Y1+Y2;            %Calculates sin(x)+cos(x)
Y4=Y1-Y2;            %Calculates sin(x)-cos(x)

Note that the above script clears the command window and variable workspace. It also closes any open Figures. After running the script, we will have X1, Y1, Y2, Y3 and Y4 loaded in the workspace. Next, select File > New > Figure, a new Figure window will open. Click "Show Plot Tools and Dock Figure" on the tool bar.

PlotTools
Figure 3.5
Plot Tools

Under New Subplots > 2D Axes, select four vertical boxes that will create four subplots in one figure. Also notice, the five variables we created earlier are listed under Variables.

Plot Tools
Figure 3.6
Creating four sub plots.

After the subplots have been created, select the first supblot and click on "Add Data". In the dialog box, set X Data Source to X1 and Y Data Source to Y1. Repeat this step for the remaining subplots paying attention to Y Data Source (Y2, Y3 and Y4 need to be selected in the subsequent steps while X1 is always the X Data Source).

PlotTools
Figure 3.7
Adding data to axes.

Next, select the first item in "Plot Browser" and activate the "Property Editor". Fill out the fields as shown in the figure below. Repeat this step for all subplots.

PlotTools
Figure 3.8
Using "Property Editor".

Save the figure as sinxcosx.fig in the current directory.

PlotTools
Figure 3.9
The four subplots generated with "Plot Tools".

SubPlot
Figure 3.10
The four subplots in a single figure.

Three-Dimensional Plots

3D plots can be generated from the Command Window as well as by GUI alternatives. This time, we will go back to the Command Window.

The plot3 Statement

With the X1,Y1,Y2 and Y2 variables still in the workspace, type in plot3(X1,Y1,Y2) at the MATLAB prompt. A figure will be generated, click "Show Plot Tools and Dock Figure".

Plot
Figure 3.11
A raw 3D figure is generated with plot3.

Use the property editor to make the following changes.

Plot
Figure 3.12
3D Property Editor.

The final result should look like this:

Plot
Figure 3.13
3D graph of x, sin(x), cos(x)

Use help or doc commands to learn more about 3D plots, for example, image(x), surf(x) and mesh(x).

Generate Code

A code can be generated to reproduce the plots. To initialize this process, recall sinxcosx.fig and select File > Generate Code.

GenerateCode
Figure 3.14
Generating code to reproduce a plot.

GenerateCode
Figure 3.15
M-Code generation in progress.
function createfigure2(X1, Y1, Y2, Y3, Y4)
%CREATEFIGURE2(X1,Y1,Y2,Y3,Y4)
%  X1:  vector of x data
%  Y1:  vector of y data
%  Y2:  vector of y data
%  Y3:  vector of y data
%  Y4:  vector of y data

%  Auto-generated by MATLAB on 05-Oct-2011 12:43:49

% Create figure
figure1 = figure;

% Create axes
axes1 = axes('Parent',figure1,'YGrid','on','XGrid','on',...
    'Position',[0.13 0.791155913978495 0.775 0.11741935483871]);
box(axes1,'on');
hold(axes1,'all');

% Create title
title('Graph of sin(x)');

% Create xlabel
xlabel('x');

% Create ylabel
ylabel('Sin(x)');

% Create plot
plot(X1,Y1,'Parent',axes1,'DisplayName','Y1 vs X1');

% Create axes
axes2 = axes('Parent',figure1,'YGrid','on','XGrid','on',...
    'Position',[0.13 0.572069892473118 0.775 0.11741935483871]);
box(axes2,'on');
hold(axes2,'all');

% Create title
title('Graph of cos(x)');

% Create xlabel
xlabel('x');

% Create ylabel
ylabel('Cos(x)');

% Create plot
plot(X1,Y2,'Parent',axes2,'DisplayName','Y2 vs X1');

% Create axes
axes3 = axes('Parent',figure1,'YGrid','on','XGrid','on',...
    'Position',[0.13 0.352983870967742 0.775 0.11741935483871]);
box(axes3,'on');
hold(axes3,'all');

% Create title
title('Graph of sin(x)+cos(x)');

% Create xlabel
xlabel('x');

% Create ylabel
ylabel('Cos(x)+Sin(x)');

% Create plot
plot(X1,Y3,'Parent',axes3,'DisplayName','Y3 vs X1');

% Create axes
axes4 = axes('Parent',figure1,'YGrid','on','XGrid','on',...
    'Position',[0.13 0.133897849462366 0.775 0.11741935483871]);
box(axes4,'on');
hold(axes4,'all');

% Create title
title('Graph of sin(x)-cos(x)');

% Create xlabel
xlabel('x');

% Create ylabel
ylabel('Sin(x)-Cos(x)');

% Create plot
plot(X1,Y4,'Parent',axes4,'DisplayName','Y4 vs X1');

As you can see, the file assumes you are using the same variables originally used to create the graph, therefore the variables need to be passed as arguments in the future executions of the generated code.

Summary of Key Points

  1. plot(x, y) and plot3(X1,Y1,Y2) statements create 2- and 3-D graphs respectively,

  2. Plots at minimum should contain the following elements: title, xlabel, ylabel and legend,

  3. Annotated plots can be easily generated with GUI Plot Tools,

  4. MATLAB can generate code to reproduce plots.

3.2Problem Set*

Problem Set for Graphing with MATLAB

Plot y=a+bx , using the specified coefficients and ranges (use increments of 0.1):

  1. a=2 , b=0.3 for 0≤x≤5

  2. a=3 , b=0 for 0≤x≤10

  3. a=4 , b=-0.3 for 0≤x≤15

  1. a=2; b=.3; x=[0:.1:5]; y=a+b*x; 
    plot(x,y),title('Graph of y=a+bx'),xlabel('x'),ylabel('y'),grid
    

  2. a=3; b=.0; x=[0:.1:10]; y=a+b*x; 
    plot(x,y),title('Graph of y=a+bx'),xlabel('x'),ylabel('y'),grid
    

  3. a=2; b=.3; x=[0:.1:5]; y=a+b*x; 
    plot(x,y),title('Graph of y=a+bx'),xlabel('x'),ylabel('y'),grid
    

Plot the following functions, using increments of 0.01 and a=6 , b=0.8 , 0≤x≤5 :

  1. y=a+xb

  2. y=axb

  3. y=asin(x)

  1. a=6; b=.8; x=[0:.01:5]; y=a+x.^b; 
    plot(x,y),title('Graph of y=a+x^b'),xlabel('x'),ylabel('y'),grid
    

    2a

  2. a=6; b=.8; x=[0:.01:5]; y=a*x.^b; 
    plot(x,y),title('Graph of y=ax^b'),xlabel('x'),ylabel('y'),grid
    

    2a

  3. a=6; x=[0:.01:5]; y=a*sin(x); 
    plot(x,y),title('Graph of y=a*sin(x)'),xlabel('x'),ylabel('y'),grid
    

    2a

Plot function _autogen-svg2png-0017.png for _autogen-svg2png-0018.png using increments of _autogen-svg2png-0019.png

x = pi/100:pi/100:10*pi;
y = sin(x)./x;
plot(x,y),title('Graph of y=sin(x)/x'),xlabel('x'),ylabel('y'),grid
PlotExercise
Figure 3.15
Graph of _autogen-svg2png-0020.png

Data collected from Boyle's Law experiment are as follows: (Data available for download.)

Table 3.1.
Volume [cm^3]Pressure [Pa]
7.34100330
7.24102200
7.14103930
7.04105270
6.89107400
6.84108470
6.79109400
6.69