Home page
 


5 Graphics

Matlab offers extensive facilities for displaying vectors and matrices as graphs. In this section we will describe a few of the most important graphics functions and provide examples.

5.1 Creating a Plot

The plot function can be used in different ways, depending on the input argument(s). 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 we specify two vectors as arguments, plot(x,y) produces a graph of y versus x.

For example, here is how to plot the cosine function from 0 to 2p.

» theta=0:pi/100:2*pi;

» y=sin(theta);

» plot(theta,y) % Check the plot on your screen

 

You can easily create multiple graphs with a single call to plot function by using multiple x-y pairs. For example, here is how to plot sine and cosine functions together over 0 to 2p.

» theta=0:pi/100:2*pi;

» y1=sin(theta);

» y2=cos(theta);

» plot(t,y1,t,y2)

 

title command adds a title text of your choice, to the top of the current axis as your graph’s title. The title text must be enclosed in single quotes.

» title('sine(t) and cosine(t)')

 

xlabel('text') and ylabel('text') commands add label texts beside the x and y-axes respectively, on the current axis. If you need to use a single quote sign ' in the title or label texts you should put it twice.

» xlabel('Angle ''Theta''')

» ylabel('Amplitude')

 

The hold on command holds the current plot and so that you can overlay several plots. The hold off returns to the default mode whereby plot commands erase the previous plots before making new plots.

The grid on command adds grid lines to the current axes and the grid off command takes them off.

Both hold and grid commands without any arguments toggle the hold and grid states respectively. To explore these functions, issue the following lines one by one and see what happens.

» x=1:20;

» plot(x,x.^2)

» hold on

» plot(x,2*x)

» grid on

 

The subplot function allows you to display multiple plots in the same figure window. Typing subplot(m,n,p) breaks 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, we can make two plots in two different subregions of the same figure window as follows.

» theta=0:pi/100:2*pi;

» subplot(2,1,1);plot(sin(t))

» subplot(2,1,2);plot(2*sin(t)+cos(t))

 

6 Loops

In this section of the tutorial, we will show how “for” and the “while” loops are used in Matlab. First, we discuss the “for loop” with examples for row operations on matrices and for Euler's Method to approximate an ordinary differential equation (ODE). Following the “for loop”, we will see the use of “while loop” in an example.

For loops allow us to repeat a group of commands. If you want to repeat some action in a predetermined way, you can use a “for loop”. As a “for loop” will have Matlab loop around some statements, and you must tell Matlab where to start and where to end. All of loop structures in Matlab start with a keyword such as “for” or “while” and they all end with the keyword “end”. Here is the format of the “for loops”.

for loopvar = expression,

statement, ..., statement

end

 

In the “for” statement or loop, Matlab will loop through for each possible value of the variable loopvar. For example, here is a simple loop that Matlab will go around 3 times.

» for j=1:3,

   j

end

 

j =

 

     1

 

j =

 

     2

 

j =

 

     3

 

As another example, let us define a vector and later change its entries in a for loop.

» v=1:3:10;

 

v =

 

     1     4     7    10

 

» for j=1:4,

     v(j)=j;

end

» v

 

v =

 

     1     2     3     4

 

NOTE: Since Matlab is an interpreted language, for loops get executed very slowly. Therefore, if speed is a constraint on your Matlab code, try to avoid using “for loops” where possible.

Yet another example is below, in which we perform an operation on the rows of a matrix repeatedly. We want to start at the second row of the matrix and subtract the previous row from it and then repeat this operation on the following rows. A simple “for loop” will do the job for us.

» A=[[1 2 3 4]' [3 2 1 4]' [2 1 3 4]']

 

A =

 

     1     3     2

     2     2     1

     3     1     3

     4     4     4

 

» for j=2:4,

    A(j,:) = A(j,:) - A(j-1,:);            % Suppressing output

end

» A

 

A =

 

     1     3     2

     1    -1    -1

     2     2     4

     2     2     0

 

Another example where loops come in handy is the approximation of differential equations. The following example approximates the solution of differential equation

 

using Euler's method over an interval from 0 to 2. (Actually, this is an initial value problem.) Euler's method simply uses the following approximation to solve such a differential equation.

 

First, we define the step size, h, then we find the grid points, and do an approximation using a for loop. The approximation is simply a vector, y, in which the entry y(j) is the approximation to function y(t) at x(j).

» h=0.1;

» x=0:h:2;

» y=0*x;            % Initialization of y (Filled with zeros)

» y(1)=1;           % Initial value

» size(x)

 

ans =

 

     1    21

 

» for i=2:21,

    y(i) = y(i-1) + h*(x(i-1)^2 - y(i-1)^2);

end

» plot(x,y)

» plot(x,y,'go')

» plot(x,y,'go',x,y)

 

The “while loop” has the following format.

while expression

statement, ..., statement

end

 

As long as the expression returns a result whose real part has all non-zero elements, the statements are executed. The expression is usually includes relational operators such as ==, <, >, <=, >=, or ~=. For information about these operators, type help relop at the Matlab prompt.

To illustrate the use of while loops, we will find an approximate solution for the following differential equation

 

by again using Euler’s method.

» h = 0.001;       % A small step size

» x = 0:h:2;

» y = 0*x;

» y(1) = 1;

» i = 1;

» size(x)

 

ans =

 

           1        2001

 

» max(size(x))

 

ans =

 

        2001

 

» while(i<max(size(x)))

    y(i+1) = y(i) + h*(x(i)-abs(y(i)));

    i = i + 1;                        

end

» plot(x,y,'go')

» plot(x,y)

 

7 Programming in Matlab

In this section, we will introduce you the basic operations for creating script or batch files in Matlab. Once you formulate specific tasks that you want to carry out in Matlab, you can group them in a file to identify them as a routine that you can use whenever you need. These Matlab script files are commonly referred as M-files and they must have “.m” as their extension to be properly identified by Matlab.

Suppose, you have developed a set of instructions to plot the cosine function over a certain interval, but later you have realized that you may use the same set of instructions to plot the cosine function over different intervals. Let us see how we can create a simple mfile to implement this idea. First, you will need to create the file. You can use any text editor to create the file but we prefer to use a very functional Editor/Debugger that comes with Matlab. This editor allows you to create m-files, to do file manipulations and to debug your programs. You can start this editor in two ways. At Matlab command prompt, issue edit command or on the Matlab toolbar, just click on the “new file icon”. If you want edit an already existing m-file, either use edit filename or click on the “open file” icon on the Matlab toolbar and select your file.

Once the editor appears on the screen, you can either type or copy and paste some commands from Matlab command window into your m-file.

In our sample m-file below, we first created an angle vector th, having values from 0 to x, and then we took the cosine of that vector and plotted it. After we were done with typing/editing, we saved this file as “mycos.m”, under a directory, let us say, C:\Myfiles.

% file: mycos.m

%

% This Matlab file will plot cos(th) function from 0 to x

% To run this file you must specify the final value, x

 

th = 0:pi/100:x;

y = cos(th);

plot(th,y);title('cosine(x)')

 

To have Matlab execute commands in our m-file, we simply type its name cosx at Matlab prompt. However, we must make sure that Matlab can find our m-file in advance. We can do this by either switching to the directory where tour m-file resides, by using the change directory, cd, command, or by adding the directory of our file to Matlab’s search path. Both of these techniques are shown below.

» cd C:\Myfiles

» mycos

» path(path,'C:\Myfiles')

» mycos

 

If you call the m-file without first defining the variable x, you will get an error message. You must first specify all of the variables that are not defined in the file itself.

» x=pi;mycos

 

Writing m-files is not the only way to prepare programs that Matlab can run, we can also write Matlab functions. Most of the time, functions are more advantageous over m-files. When we pass a variable to a function as an input argument, its content and will not change. Functions return their results or outputs into variables of our choice. Also, a function may run much faster than an mfile doing the same job.

The commands and functions that will form a new function must be put in a file whose name defines the new function, with a filename extension of “.m”. At the top of the file there must be a line that contains the syntax definition for the new function. For example, let us write our “cosine plotter program” in function form.

function mycosfun(x)

% file: mycosfun.m

% This Matlab function will plot cos(th) from 0 to x

% Input vars : x, the final value

% Output vars: none

th = 0:pi/100:x;

% th is a local variable, it will get lost after

% the functions returns

y = cos(th);

plot(th,y);title(‘cosine(x)’)

 

8 Help and Online Documentation

8.1 Help Utilities of Matlab

Matlab offers extensive help through several facilities. These are:

·       lookfor

This utility lets you search all m-files in Matlab’s search path for a keyword, so that you can locate Matlab function(s) that you can use for a specific task. Here is an example.

» lookfor cosine

ACOS   Inverse cosine.

ACOSH  Inverse hyperbolic cosine.

COS    Cosine.

COSH   Hyperbolic cosine.

TFFUNC time and frequency domain versions of a cosine modulated Gaussian pulse.

 

·       help

This utility lets you reach the on line help service of Matlab.

help, by itself, lists all primary help topics. Each primary topic corresponds to a directory name on Matlab’s search path or Matlabpath (for more information about Matlabpath, type help path at the Matlab prompt.)

help topic gives help on the specified topic. The topic can be a command/function name or a directory name. If the topic is a command/function name, help displays information about that command/function, like its syntax, behavior, examples of usage, etc. If the topic is a directory name, help displays the table of contents for the specified directory.

Here is an example.

» help cos

 

 COS    Cosine.

    COS(X) is the cosine of the elements of X.

 

NOTE: In the online help, keywords are capitalized to make them stand out. Always type commands in lowercase in order Matlab since all command and function names are actually in lowercase.

For more information about the help utility, type help help at Matlab prompt.

·       The Matlab Help Desk

This is an online help system that you can browse through using your regular web browser. The Matlab Help Desk provides access to a wide range of help and reference information stored on a disk or CD-ROM in your local system. The Help Desk can be started by selecting Help Desk option under the “Help” menu, or by typing helpdesk at the prompt.

At the end of tutorial, we are presenting you with some website links and books that your may find useful.

 

8.2 WWW Sites on Matlab

1.    Matlab’s official web site: http://www.mathworks.com

2.    Useful Matlab M-Files and Toolboxes: http://www.mathtools.net

3.    An extensive Matlab FAQ by Mathworks: http://www.mathworks.com/FAQ/faq.html

4.    University of Florida Matlab Primer: http://www.cis.yale.edu/secf/software/Matlab/Matlab-primer.html

5.    City University of Hong Kong, A Beginner's Guide to Matlab: http://www.image.cityu.edu.hk/Matlab/Matlab-b.pdf

6.    Useful Matlab links and materials: http://www.phys.ualberta.ca/~kbeaty/Matlab_help/weblinks.htm

7.    Matlab Links on the web by Malgorzata S. (Gosha) Zywno: http://www.ryerson.ca/~ele749/general/Matlablinks.html

 

8.3 Books about How to Use Matlab

All from Prentice-Hall,

http://www.prenhall.com/divisions/esm/catalog.html

1.    Mastering Matlab, A Comprehensive Tutorial and Reference, by D. Hanselman and B. Littlefield, 1996.

2.    The Student Edition of Matlab, by The MATHWORKS, Inc., 1996.

3.    Engineering Problem Solving With Matlab, by D. Etter, 1997.

4.    Matrices and Matlab: A Tutorial, by M. Marcus, 1993.

5.    Matlab Project Book For Linear Algebra, R.L. Smith, 1997.

6.    ATLAST Computer Exercises for Linear Algebra, S. Leon, et.al, 1996.

 

      Research      My CV    Downloads      Publications      My Family