Vous êtes sur la page 1sur 28

An Introduction to Programming

in

MATLAB

by

Robert P. Hansen
TABLE OF CONTENTS

I. Introduction ................................................................ 3

II. An Overview of How to Use MATLAB


Single Calculations ..................................................... 3
Sequential Workspace Operations ............................... 5
Program Files ........................................................... 6

III. MATLAB Program Structure


General ..................................................................... 6
Integer Versus Real ..................................................... 6
Program Components - Script and Function Files ........ 6

IV. MATLAB Programming Language


General Syntax and Format.........................................… 8
Math Operations ........................................................... 8
Control Statements ....................................................… 10
Input and Output Statements ........................................ 11

V. Graphics
General ........................................................................ 14
XY Plots ....................................................................... 15
XYZ Plots ................................................................... 16
Multiple Graphs .......................................................... 18
Animation .................................................................. 19

Appendix A - Glossary of Useful Commands ............................ 23


Appendix B - Sample XYZ Plots ...........................................… . 27
Appendix C - Sample Programs ................................................ 28
I. INTRODUCTION

MATLAB stands for matrix laboratory. It consists of a set of easy to use


engineering and scientific functions and powerful graphics/plotting commands in an
environment that includes its own programming language. The programming language
most closely resembles the language C. This document will attempt to introduce the
MATLAB programming language by comparison to familiar concepts in Turbo Pascal.

A more in-depth explanation of MATLAB fundamentals may be found in the


MATLAB User's Guide. A complete listing of commands is printed in the MATLAB
Reference Guide. This introduction covers the key commands and features in MATLAB
version 4.2b. A math coprocessor, 8 megabytes of hard disk space, and at least 4
megabytes of extended memory are required for this version. To adequately use 3D
graphics and movies, 8 megabytes are recommended. Microsoft Windows 3.1 or higher is
also required.

II. AN OVERVIEW OF HOW TO USE MATLAB


To immediately see how to use MATLAB, you should review the demonstrations
available by typing demo at the MATLAB prompt. You can employ MATLAB in a
variety of ways, some of which are discussed below.

SINGLE CALCULATIONS

Think of how you use your calculator. Not what MATLAB was designed for, but it can
come in handy. Just type in the operation you want and hit return:

>> 100 / 5 (return)

ans =
20

MATLAB returns your answer as the default variable ans. The variable ans is now a
variable stored in MATLAB's memory and may be used in additional operations by only
referring to the variable name. Numerous intrinsic functions may also be used in single
calculations or, as you will see, in a MATLAB program. The MATLAB Reference Guide
has a complete list of intrinsic functions and other commands. For example, to obtain the
natural logarithm of the quotient above:

>> log (ans) (return)


ans =
2.9957

If you want to preserve the number stored in ans for future use, you could assign a
variable name of your choice to the operation:

>> x = log(ans) (return)

x =
2.9957

The above examples all resemble scalar operations, that is each operation acts on only one
number and returns only one number. All variables in MATLAB are in fact matrices or
vectors. The above example just happens to involve matrices that are 1 x 1, so for all
practical purposes you can consider them scalars. The real strength of MATLAB is in its
ability to do all operations with vectors and matrices. A matrix may be read from a data
file, generated from MATLAB commands, or typed in as below.

>> A = [1 2 3; 4 5 6; 8 8 9] (return)

A=

1 2 3
4 5 6
8 8 9

Note that the above format separates only the rows with a semicolon, a space separates
the elements within each row. Any imaginable matrix operation may now be performed
on A. For example,

>> B = inv(A); (return)


>> B * A (return)

ans =

1 0 0
0 1 0
0 0 1 (.... as you should have guessed)

Did you notice the subtle difference in the above example? The first operation was ended
with a semi-colon. The semi-colon, when used at the end of a statement, suppresses
output of the answer. Therefore, the matrix B was not returned. These types of matrix
operations have no equivalent in Turbo Pascal. The MATLAB matrix operations are
always available, they are part of the MATLAB software. In Turbo Pascal, an operation
such as an inverse must be explicitly written as a function or procedure, or exist as a unit.
In any event, commands for matrix operations do not come with Turbo Pascal software.

SEQUENTIAL WORKSPACE OPERATIONS

For every variable you generate through single commands as shown above,
MATLAB stores its name and contents in an area of memory called the workspace. By
typing a series of individual commands, a small program can be executed and the variables
will be stored in the workspace. For example, let’s generate a small program to plot a
function of x over the range 0 ≤x ≤3 .

>> x = 0 : 0.2 : 3.0;


>> y = x .^ 2 - 4;
>> plot (x, y)

The result of these lines will be a separate graphics window appearing with a graph of x
versus the function x2-4 . The first statement generates a vector of values for x starting
with zero in increments of 0.2 to 3.0 . The second line generates function values for each
value of x and stores them in y. The final statement plots the first value in x against the
first value in y, and so on. A new concept here is the use of the period in front of the
power operator "^". Since x is a vector, x^2 would imply an illegal operation. What is
really desired is to square each element of the vector. Placing a period in front of any
mathematical operator tells MATLAB the operation is to be element by element. As long
as you do not exit MATLAB, or reassign the variables, you could simply repeat the
plot(x,y) command to regenerate the plot. A very useful keystroke is the up-arrow. It
will recall previous statements saving you the time it takes to retype a command.

Upon exiting MATLAB, all variables stored in the workspace are erased. If you
want to save the variables and their values for future work, use the save command. For
example, save temp will save all the workspace variables in a file called temp.mat . The
variables may be retrieved during future MATLAB sessions by entering load temp. The
plot command could then be re-entered to generate the graph.

The above example is only a crude program. It lacks control structure and is
limited to execution of commands in sequential order. This technique is therefore limited
to solving simple problems requiring only a few commands. To solve more complex
problems, commands must be saved into a special file just as you would save a Turbo
Pascal program in a .pas file. The MATLAB program file is the M-file.

PROGRAM FILES

An M-file is to MATLAB as a file with a .pas extension is to Turbo Pascal. Disk


files that contain MATLAB statements are called M-files because they carry the file
extension .m as part of the filename. M-files can call other M-files. Many of the
functions in MATLAB are in fact M-files. The closest analogy in Turbo Pascal is the
Turbo Pascal Unit, a type of program that can be used by other programs.

There are two classes of M-files -- script files and function files. A script file is
directly analogous to a Turbo Pascal program file, but may also perform analogous to a
Turbo Pascal procedure. A MATLAB function file is just like a Turbo Pascal function - it
returns only a function value. The remainder of this document will describe M-files in
detail.

III. MATLAB PROGRAM STRUCTURE

GENERAL

The MATLAB programming language is similar to the language C. The


appearance of MATLAB "code" is not much different from any other programming
language you may be familiar with. You will hopefully find the MATLAB language less
restrictive and more powerful than Turbo Pascal. Your knowledge of any programming
language will help you learn MATLAB quickly.

INTEGER VERSUS REAL

One of the ways that MATLAB is less restrictive than other languages is its
treatment of real and integer numbers. All number are stored, and all calculations are
performed, in double precision. All MATLAB variables are considered real, but if a
variable is an exact integer it will be displayed without a decimal point. You, therefore,
do not have to declare any variables, which allows you to get to the heart of your program
that much quicker. You also never have to worry about "mixed mode" operations that can
cause hidden problems in other programming languages. To round a MATLAB variable
to the nearest integer use the round command.

PROGRAM COMPONENTS - SCRIPT and FUNCTION FILES

If you recall your Turbo Pascal education, you remember that there are very
distinct parts of a typical Pascal program. The main sections are the heading, declarations,
functions and procedures, and the main body. In MATLAB, there is no heading unless
you are writing a function file (this is a type of M-file). Of course, it is a good idea to
provide at least a couple of comment lines (start the line with %) that identify the author,
what the file does, and an explanation of key variables.
In Turbo Pascal the declarations section identified all variables, including arrays,
and constants. There is no declaration section in MATLAB because all variables are
considered real and the matrix space is automatically created as you use the variable. As
an example, the statement x = 0 : 0.5 : 2.0 creates a 1 by 5 matrix where x(1)=0,
x(2)=0.5, ... etc. To accomplish this same task in Turbo Pascal would require a statement
in the declarations section and at least one other line of code (most of you would probably
use up to four more lines of code). Thus, MATLAB does in one line what Turbo Pascal
needs at least two to accomplish. This is one of the powerful features of the MATLAB
language -- it takes care of much of the memory management the programmer has to deal
with in other languages.
The functions and procedures section is the largest portion of a Turbo Pascal code
and are required to appear before the program main body. There is no such structure
requirement in the MATLAB language. The equivalent of a procedure in MATLAB is a
script file. It would look similar to a procedure, but exists as a separate .m file. For
example, look at the simple script file below:

generate
plotdata
y = mean(x)

This file is the equivalent of a main body. Each line in the file is the name of
another M-file. The first two are script files and the third is a function file. The script files
do not "pass" variables from the main body to the script file. They do not need to because
all the variables in script files are in the workspace which makes them global (all files have
access to them). The main body looks for the file generate.m in the current directory and
executes all of the commands in it. It does this for all M-files in the script file.
The third line is a function file because it needs an input to act on. In this case, x is
a variable that is created by an earlier command and mean.m contains the commands to
calculate the mean of the numbers contained in x. Unlike the script file, the variables in
the function file are only local and do not reside in the workspace. The function file does
have one special format requirement -- the very first line must declare the function name
with input and output arguments. For this example, the first line in mean.m would be:
function y = mean(x). This particular function already exists in MATLAB and may be
viewed by entering type mean.m .
All of the commands in each file could have been written in one file, but this
violates the top-down programming approach and makes the file hard to read and to
troubleshoot. As most of us were taught, you should strive to have the main body script
file read as a list of tasks and functions that are themselves other M-files.

IV. MATLAB PROGRAMMING LANGUAGE

GENERAL SYNTAX AND FORMAT


The MATLAB programming language has a minimum of syntax requirements.
Here are some of the major requirements that are applicable to all statements. A
MATLAB command may start anywhere on the line. If a statement requires more than
one line if may be continued onto a second line by adding three periods (...) to the end of
the first line. Multiple statements may be included on the same line by separating
statements with a comma. This should be used sparingly, as it tends to make a program
difficult to read.
As already mentioned, MATLAB will immediately return the results of a command
to the MATLAB window unless the command is ended with a semicolon. You may view
intermediate results by dropping the semi-colon on selected commands. Unlike Turbo
Pascal, numbers do not need leading zeros. For example, using the number .25 or 0.25 is
legal in MATLAB. Comment statements may be used anywhere in the program by using
the symbol %, including on the same line as a command. Comments may be added to the
last example as follows:

generate % generate values for velocity and acceleration


plotdata % plot velocity and acceleration versus position
y = mean(x) % calculate the mean value of the vector x

MATLAB is case sensitive. Variables may be uppercase, lower case, or a mixture of


cases. The variable A is not the same as a. All function names must be lowercase; inv(A)
inverts the matrix A, INV(A) references an undefined function.

MATH OPERATIONS

Operators and Functions

MATLAB uses standard math operators similar to Turbo Pascal. The range of
numbers that MATLAB can handle is roughly 10-308 to 10308. The standard math
operators are:

+ addition * multiplication ^ power


- subtraction / division

A complete set of scientific and engineering functions are available. A partial list is in
Appendix A.

Matrix Operations

The character ‘(prime or apostrophe) denotes the transpose of a matrix. When


applied to a vector the statement
x = [ 3 -5 2]’

results in
x=
3
-5
2

Addition and subtraction are defined if the matrices are the same size. The
exception is when a scalar (a 1x1 matrix) is added to or subtracted from any other matrix.
In this case, the scalar is added or subtracted from all elements of the other operand.
Matrix multiplication is carried out by the symbol *, but is only defined when the
inner dimensions of the operands are the same. Thus, A*B is only legal if A has as many
columns as B has rows. The dot (or scalar) product of two vectors of equal length may be
obtained by x’* y.
Matrix division is not a defined operation. The symbol \ may be used to perform
an inverse and a multiplication with one operator. Thus x = A\B means inv(A)*B and
represents the solution of the system of equations given by Ax = B.
Using the symbols .*, ./, or .^ indicate an element by element operation.

Vectors are easily generated using the colon (:). The statement x = 1: 2 : 9 gives
x=
1 3 5 7 9

Smaller or larger matrices can be generated from any given matrix. If two matrices have
the same number of rows, the statement

X = [ A B]

augments matrix A with the rows of matrix B. The first three rows of matrix A may be
extracted by

X = A ( 1:3 , : )

The second colon above implies all columns. Once a matrix has been stored, any element
may be individually addressed by using index notation similar to Turbo Pascal. A(1,3) or
X(2, 5) are examples of notations that could be used in any statement.

CONTROL STATEMENTS

Repetitive Statements
The two types of repetitive statements in MATLAB are the FOR loop and
the WHILE loop. These types of control statements are essentially equivalent to their
Turbo Pascal counterparts. There is no equivalent of the Pascal REPEAT/UNTIL
statement in MATLAB. The MATLAB FOR loop has the format

for i = 1 : n
statements
end

The index variable (i in this case) does not have to start at one, and can end at any number
or variable. If a step size other than one is required, the format for i=1:m:n may be used,
where m is the step size (which may be negative). Each FOR statement must have a
matching end statement. The FOR statements may be nested.

Conditional Statements

The WHILE statement in MATLAB is just like its counterpart in Turbo


Pascal. It allows the repeated execution of a command or group of commands until a
condition is satisfied. The general format is :

while expression
statements
end

The MATLAB IF statement is also very similar to Turbo Pascal. The


elseif statement may be used as many times as needed in conjunction with the if
statement. The format is:

if expression
statements
elseif expression
statements
else
statements
end

The BREAK statement may be used inside of an IF or WHILE loop to stop


execution of that loop.

Relational and Logical Operators

The examples above that use an expression need some type of relational or
logical operator. MATLAB uses the following relational operators:
== equal > greater than >= greater than or equal to
~= not equal < less than <= less than or equal to

The following are logical operators:

& AND. | OR.


~ NOT. xor EXCLUSIVE OR.

INPUT AND OUTPUT STATEMENTS

Screen Input/Output

Let's consider the situation where you want to write a program that will accept
input from, and output variables and messages to, the screen . A text message may be
written to the MATLAB Command Window at any point in a program by simply including
the text enclosed in single quotes (') as a separate line in your program. For example, to
let the user know that a particular operation is taking place you might include in your
program the line:

'The matrix inverse is now being computed'

This grouping of text now becomes a string variable, and every variable must have a name.
MATLAB thus assigns the default variable name to the string and produces a rather crude
output of the form:

ans =

The matrix inverse is now being computed

MATLAB uses this as a quick default format. This format may not be suitable for all
applications. To show only the desired text, the fprintf must be used. The command:

fprintf ('The matrix inverse is now being computed')

will print the desired text without also showing an unwanted variable name. To create an
output where a number variable and a string variable are on the same line, the variable
must be converted to a string as in the following example:

fprintf (['The magnitude of velocity is ', num2str(vel)])

This example assumes a variable named vel already exists. The text must be set off with
single quotation marks ('). The command num2str converts a number to a string, so that it
may be manipulated as text. The brackets ([ ]) in the above example tell MATLAB to
concatenate (combine) the two strings. Greater control of the numerical and text output
may be achieved by using escape and conversion characters described in the next section.

Now assume you want the program user to input velocity. The format is:

variable name = input ('prompt')

For the above example, we could allow the user to enter the velocity by including the line:

vel = input ('Please enter the projectile velocity now')


MATLAB will write the prompt and wait for the user to type in a number that will be
assigned to the variable vel. A string variable may also be input by using the format:

variable name = input ('prompt', 's')

The 's' qualifier tells MATLAB to store the user input as a string.

File Input/Output

Similar to Turbo Pascal, files must first be opened before they can be
written to or read from. The format to open a file is:

fid = fopen ('filename', 'permission')

The left side of the expression may be any name. MATLAB will assign a non-negative
integer to this variable if the file is successfully opened. If the file is not successfully
opened, fid is set to -1. The filename must be the full name of the file, including the
extension and path if it is not in the MATLAB directory. The permission strings available
are 'r' for reading, 'w' for writing, 'a' for appending, and 'r+' for both reading and writing.
After completing the read or write operations close the file using fclose(fid).
The format for writing to a file is :

fprintf (fid, 'format', matrix)

The example below illustrates the use of this command. The statements below produce a
table of values for the powers of e.

x = 0:.1:1;
y = [x; exp(x)];
fid = fopen('expon.dat','w');
fprintf (fid, 'Exponential Function\n\n');
fprintf (fid, '%6.2f %12.8f\n', y);
fclose(fid);
The output written to expon.dat is:

Exponential Function

0.00 1.00000000
0.10 1.10517092
...
1.00 2.71828183

The 'format' specification in the above format may contain any text you want along with
special strings called escape characters and conversion characters. The escape character is
always preceded by a backslash (\). The example here uses \n which is the escape
character to go to a new line. Possible escape characters include:

\n new line
\t horizontal tab
\b backspace
\r carriage return
\f form feed
\\ backslash
\' single quote

The conversion characters are always preceded by the character %, and allow precise
format for numerical output. The general format for the conversion character is :

% width.precision notation

The width.precision specifier is optional. If omitted, MATLAB will use a default value.
Width is the total number of characters allotted for the output of the number, and
precision is the number of digits to the right of the decimal to be output. The width may be
positive or negative. A positive width will right-justify the output within the field width, a
negative number will left-justify the output. The possible choices for notation are:

e exponential notation
f fixed point notation
g e or f notation, whichever is shorter

The fprintf command can also be used to provide formatted output to the screen by not
including the file identifier (fid) in the above format. Alternatively, the file identifier could
be set to one, which is the default for output to the screen.

To read a formatted file, use the fscanf command as follows:

A = fscanf (fid, 'format', size)


The data that is read will be placed into a matrix that you name (A is just an example, any
legal variable name may be used). The fid specifier is the file identifier assigned by
MATLAB during the fopen command. The simplest form of the 'format' specifier is
%notation, where notation is either e, f, or g as described above. The size specifier is
optional. If not specified, the entire file is read into a column vector. If specified, the
valid entries are:
n read n elements into a column vector
inf read to the end of the file, resulting in a column vector containing
the same number of elements as are in the file
[m,n] read enough elements to fill an m x n matrix, filling the matrix in
column order. n can be inf, but not m.

It is very important to be aware of the information in bold immediately above. The fscanf
command will cause MATLAB to begin reading a file from left to right, and top to
bottom. As each element is read, it is loaded into the matrix by filling each column first.
This is a convention used in other programs also, but it has the effect of storing the
transpose of the matrix you just read. Let's assume we have a file with only the numerical
data of the previous example (the table of exponential values). To read this file and
reproduce it on the screen requires the following commands:

fid = fopen ('expon.dat', 'r');


B = fscanf (fid, '%f %f'', [2,11]);
table = B'
fclose (fid);

The original table in file expon.dat contained 11 rows by 2 columns of data. The fscanf
command specifies the size as 2 rows by 11 columns. Because MATLAB fills the B
matrix in column order, the first row of B will contain all the values of x, and the second
row will contain the corresponding values for ex. Thus, to reproduce the original 11 x 2
table, the transpose of B is taken. This is a long explanation for what turns out to be a
simple rule -- when reading tabular data from a file, state the size specifier in fscanf as
[columns, rows], then take the transpose.

V. GRAPHICS

GENERAL

The quickest way to learn about the types of graphs available and the commands to
produce them is by looking at the MATLAB demo. Just type demo at the MATLAB
prompt. Click on "Visit" under "MATLAB". Then click on "Select a demo" under
"Visualization" and select one of the options. Once you understand the basics of
MATLAB described above, there is nothing new to learn to obtain graphics other than
particular commands for the plot you want.
It is helpful at this point to remind you that MATLAB considers all variables to be
vectors or matrices. The graphics in MATLAB is best employed by plotting a vector of
values in x against a vector of values in y. You can plot one point at a time, but this is
much slower than plotting vectors. The bottom line is this -- all of the data you want
plotted should already be calculated and stored into a matrix/vector before you invoke a
graphics command. There are exceptions, but this is how MATLAB was designed to be
used for best advantage.

XY PLOTS

The types of XY plots available are line, bar, stair, error bar, polar, and stem. The
line plot is executed by the command plot(x,y,'s'), where x and y are vectors of the
independent and dependent variables. The s is optional and specifies the line color and
style. If omitted, a solid, yellow line is used. Possible choices for line characteristics are*:

Symbol Color Symbol Linestyle


y yellow . point
m magenta o circle
c cyan x x-mark
r red + plus
g green * star
b blue - solid
w white : dotted
k black -. dashdot
-- dashed

* This table is taken from the MATLAB User's Guide, The MathWorks, Inc, pg. 2-58.

To plot the data from the example of section IV, use either of these commands:

plot(x,y) % creates XY plot using solid, yellow line


plot(x,y,'g--') % creates XY plot using dashed, green line

To plot multiple lines on the same graph, use the format:

plot (x1,y1,'linetype1',x2,y2,'linetype2',....)
or
plot (x1, y1, ‘linetype1’)
hold on;

plot (x2, y2, ‘linetype2’)


hold off;
Any graphics statements between the hold on and hold off commands are applied to the
last figure generated. Without them, a new figure would be generated for each plot
command.
Yet another method to place multiple plots on the same graph is to use the same
plot command with matrices. For example, plot(Y) will draw one line for each column in
matrix Y. The x-axis is labeled using the row number in this case. Similarly, if x is a
vector and Y is a matrix, plot(x, Y) will plot the rows or columns of Y versus x using
different colors for each line. MATLAB will choose whether to plot the rows or columns
based on the number of elements in x. The length of x must, therefore, match either the
number or rows or columns of Y. In the event that Y is square the columns are used.
The result of any of these commands will be a separate window with automatically
scaled axes, and the appropriate lines/symbols. Titles and axis labels may be added using
the commands:

title ('A Title of Your Choice') % centers the title at the top of the graph
xlabel (' text') % x-axis label
ylabel (' text') % y-axis label

If text is desired at a location other than where the title and axis labels are positioned, use

text (x, y, 'text') % x and y are the coordinates of the graph

Additional XY graph commands are listed in the Glossary of Useful Commands.

XYZ PLOTS

These types of graphs are also called contour, surface, or carpet plots. They are
useful for presenting some type of variable (temperature, pressure, etc.) that exists over a
two dimensional space domain. The temperature distribution over a rectangular plate is a
classic example. Since there are two space dimensions, a decision must be made how to
represent the third variable. If a two-dimensional representation is used, colors can be
used to indicate the distribution of the third variable. This is a contour plot. If the third
space dimension (the z-axis) is used to represent the variable value, this is generally called
a surface or carpet plot. MATLAB also combines the use of the third space dimension
and color to represent data.
Let's consider a 2D representation first using contours. Assume the matrix Z
contains the information you want to plot. To provide a more concrete discussion, we can
consider the numbers in the matrix Z to be temperature readings at equally spaced x
positions and equally spaced y positions along a steel plate. The simplest contour plot is
produced by contour(Z). The lower-left hand corner of the plot corresponds to the upper-
left corner of Z (i.e., Z(1,1)). The diagram below shows that you actually are viewing the
contours of an m x n matrix in a Cartesian frame.
Position of Data in Matrix Position of Data in Contour Plot

Z(1,1) Z(1,n) Z(m,1) Z(m,n)


x
y
y
x
Z(m,1) Z(m,n) Z(1,1) Z(1,n)

The axes are scaled according to the position in the matrix. For example, if Z is a 4x3
matrix, then the x-axis is scaled from 1 to 3 and the y-axis is scaled form 1 to 4. In other
words, the columns are represented along x, and the rows are represented along y. Unless
your domain dimensions just happened to correspond to the indices of the matrix, the
scaling will not match the physical dimensions you are working with. To show the true
dimensions, use contour(x,y,Z). The x and y vectors contain the actual coordinates that
correspond to each of the temperature readings in Z. The elements of x and y must be
equally spaced. The number of elements in x must be the same as the number of columns
in Z, and the number of elements in y must correspond to the number of rows in Z.

The above contour commands automatically choose what contours lines will be
drawn. To control the number and value of the contour lines shown, use:

contour (x, y, Z, n) or contour (x, y, Z, v)

The number of contour lines is specified by the parameter n. The number and value of the
contour lines shown is controlled by the values of the vector v. Other combinations of the
above inputs to the contour command are possible and discussed in the MATLAB User's
Guide. You will most likely want the values of the temperature printed next to each
contour line. To do this, use the contour commands as shown above assigned to a
variable and an additional clabel command. For example,

C = contour(x, y, Z, n);
clabel(C)

produces the contour plot with each contour line labeled in a random position. Another
format for clabel is clabel(C,V) which labels just those contours in vector V. For exact
control of the positioning of the contour labels use clabel(C,'manual') which allows
placement of contour labels selected by the mouse. Titles and axes labels may be added as
explained in the XY Plots section.
The contour command produces contours as colored lines. Contours may also be
shown as continuous color shading. The pcolor(x,y,Z) does this. The following sequence
is recommended to smoothly blend the colors and provide a scale of contour values:
pcolor (x, y, Z) % assign color to each matrix element
shading interp % smoothly blend the colored grids
colorbar % provide a legend of the value for each color

A very convenient command exists within MATLAB to generate values of a


dependent variable based on a range of two independent variables. Let's generate the
contour plot for the function z = xe − x − y over the range of − 2 ≤ x ≤2 , − 2 ≤ y ≤3. A
2 2

normal programming approach would be to establish a nested loop and cycle through all
combinations of x and y. The meshgrid command is specifically designed for use with
generation of data for XYZ plots and allows for calculation of the dependent variable for
all combinations of the independent variables without creating nested loops. The
following statements illustrate its use.

x = -2 : .2 : 2; % generates vector of 21 x values


y = -2 : .2 : 3; % generates vector of 26 y values
[X,Y] = meshgrid(x,y) % X(1,1),Y(1,1) thru X(26,21),Y(26,21)
% represent the grid of points in x-y plane
Z = X .* exp(-X .^2 - Y .^2); % compute Z at every grid point
contour (x, y, Z)

The same information can be used in a three dimensional plot, where the height
above the z axis represents the value of the dependent variable. The contour command in
the above example could be replaced by mesh(x,y,Z). The output will be a surface
representation of the value of Z as a wireframe. Instead of a wireframe, colored panels
may be used to represent the surface using surf(x,y,Z). A line contour plot may be
projected onto the x-y plane beneath the surface using meshc or surfc. The vertical axis
may be labeled on any of these plots by using zlabel('text'). Samples of the output for
contour, surf, and mesh commands are shown in Appendix B.

MULTIPLE GRAPHS

If you want to generate more than one graph during the execution of an M-file,
there are two ways to position the graphs -- using subplots within the same window or
create a window for each plot.
Let's assume we want to plot both a 2D contour and a 3D mesh from the same
data for the example above. Using subplots on the same window:

subplot (1, 2,1)


contour (x, y, Z)
subplot (1, 2, 2)
mesh (x, y, Z)
This will bring up both plots on the same window side by side. subplot (m, n, p) breaks
the window into an m x n matrix of subplots, with p being the current subplot. The
subplots are numbered from left to right and top to bottom along the window.
If separate windows are desired for each plot, each new graph command must be
preceded with figure. Without the use of figure, only the last plot requested will be
displayed. By using only figure the windows will be laid on top of each other, and it will
be up to the user to click and drag to position the windows as desired. If the same set of
graphs are repeatedly produced, it is more convenient to include a position parameter with
the figure command. The general format is :

figure ('Position', [left bottom width height] )

where left and bottom define the distance in pixels from the lower-left corner of the screen
to the lower-left corner of the figure window and width and height define the dimensions
of the window, also in pixels. For the previous example, one could use:

figure ('Position', [30 30 300 250] )


contour (x, y, Z)
figure ('Position', [350, 30 300 250] )
mesh (x, y, Z)

ANIMATION

Animation is an excellent technique to display how a variable changes over time.


In fact, with three coordinate dimensions and the use of color, animation may be
considered a way of representing a fifth dimension. All of the animations done in the
MATLAB demo are M-files using the MATLAB programming language. Looking at
these files can provide you with great insights to the more advanced animation techniques
available. There are basically two methods to create a graphics animation in MATLAB.
The first method is to use the movie feature, the other is to use the erasemode.
Any sequence of plots can be saved and then played back in a short movie using
the getframe and movie functions. The following example creates 10 frames of the
function y = te − x for 0 ≤x ≤3 for each time interval from 1 to 10.

M = moviein (10); % establish storage matrix for each frame


x = 0 : 0.05 : 3.0;
axis ([0 3 0 10]); % override auto axis scaling
title ('Sample Animation');
axis (axis) % freeze scaling at current limits
for t=1 : 10
plot (x, t.*exp(-x), 'g*')
M(:,t) = getframe; % place current figure as a pixel map into a column
end % of the M matrix.
The axis scale was set on the third line to keep the scaling the same for every frame. At
the end of this program, or at a later time, the frames can be replayed as a movie by the
command movie(M,number), where number is how many times the sequence is to be
repeated. If number is negative, the frames will be played in forward and reverse order.
The advantage of the movie function is that the animation may be replayed indefinitely
even though the data only has to be generated once. The disadvantage is that it uses a lot
of memory. MATLAB recommends no more than a few dozen frames.
As is typical of a transient analysis, you might want to display an animation of a
solution over many time steps. For this type of application, the movie function is not
practical. A method that will allow you to plot a vector of points an infinite amount of
times without running out of memory is shown below. It plots the same equation as the
movie example.

x = 0 : 0.05 : 3.0;
p = plot(x, exp(-x), 'g*', 'EraseMode', 'xor', 'MarkerSize', 4)
axis ([0 3 0 10]); % override auto axis scaling
title ('Sample Animation');
for t = 2 : 10
drawnow % execute the last graphics command now
set (p, 'XData', x, 'YData', t.*exp(-x))
end

The output is as follows. The function y = te − x is evaluated and drawn over the range of x
for t = 1. The function is then evaluated at t = 2, drawn over the range of x, and the
previous series of points for t = 1 are erased. This process repeats itself giving the
appearance of a smoothly growing function plot. By way of maintaining the "big picture",
remember that the above lines are a complete program. No other lines of code are
required to make it work. A good Turbo Pascal programmer would require at least one
page of code to produce the same output.
The second and next to last lines are the workhorses. The second line is a plot
command with two new options. It plots the function for t = 1 and establishes the format
(line color, type, and marker size) for all future operations on this plot (the default marker
size is 6). Using the EraseMode property, it also determines how the existing points on
the figure will be plotted as each new set of points is added. The values for the
EraseMode property are:

normal the entire figure is erased (including axes, labels, and titles) and
redrawn with only the new set of points. This gives a very accurate
picture, it is the slowest. Because everything is erased and
redrawn, this mode causes a "blinking" between each plot that
makes it undesirable for good animation.
none no part of the figure is erased. The new plot is added directly to the
existing figure. It is very fast and a good choice if your animation
does not require the removal of old points.
xor the new plot is added and the existing one is "covered" by drawing
over it in the background color. This produces a very smooth
effect of a line or object moving across the screen. This method
does not destroy other graphics objects beneath the one being
erased.
background same as xor but objects behind the erased object are destroyed.

By assigning the plot command to a variable (p), the identifier for this figure is stored and
available for future reference. MATLAB calls this a "handle". The drawnow command
tells MATLAB to immediately execute the last graphics command. Without the drawnow,
MATLAB completes all commands before performing any graphics operations with the
net effect of only showing you the last frame of your animation.
The set command has the general format:

set ( object handle, 'PropertyName', PropertyValue, ...)

The object in this case is the entire figure, and its handle is the variable p. As already
mentioned, the handle also contains the specifications for marker size, line color and type,
and the value or the EraseMode property. Two of the properties of the figure identify
what are the data being plotted -- their PropertyNames are XData and YData. Thus, each
call to set inside of the for loop causes another set of data points to be plotted.
Plotting symbols such as ‘*’or ‘+’will be noticeably slower than plotting a line.
The pace of the animation can be controlled by how many points or nodes are used. A
more precise way to slow the animation speed is to use the pause(n) command to delay
the execution of the program by n seconds. If the above animation runs too fast, a
pause(n) could be placed anywhere inside of the for loop to slow it down.

As a final look into MATLAB animation techniques, we will add the current value
of time with an appropriate label to the above program. The value of the variable t will be
updated on the screen as each new set of points is plotted. The additional commands
needed to do this are shown in bold below.

x = 0 : 0.05 : 3.0;
p = plot(x, exp(-x), 'g*', 'EraseMode', 'xor', 'MarkerSize', 4)
text(1.6, 8, 'Time = ') % one-time placement of text on plot
time = text(2, 8, '1','EraseMode','background')
axis ([0 3 0 10]); % override auto axis scaling
title('Sample Animation');
for t = 2 : 10
drawnow % execute graphics commands now
set(p, 'XData', x, 'YData', t.*exp(-x))
time_string = num2str(t); % convert the value of t to a string
set(time, 'String', time_string)
end
The first new line simply provides a label for the time output. The text statement writes
the label once and nothing elsewhere in the program writes to that position again. The
second new statement is directly analogous to the p =plot... statement above it. It creates
the initial string for the first time value (which is one) and establishes how the existing
output of the variable t will be erased when time is referenced again. Time is now the
“handle” for the output of t. Because the value of t changes inside of the for loop, its
value must be converted to a string before it is placed on a graph window. The function
num2str does this (in the rare event it hasn't hit you yet, this stands for “number to
string”).
The new set command is also analogous to the set (p,...) command. Following the
format for set above, the object handle is time, the 'PropertyName' to be updated is
'String', and the value it is to be updated to is time_string. Remember that the
'PropertyName' of 'String' is not a variable name -- it is a specific property associated with
text objects. Other properties that can be used are listed under the text command in the
MATLAB Reference Guide.
APPENDIX A
GLOSSARY OF USEFUL COMMANDS

The following list is a selection of the most commonly used commands and
functions. The key below lists the abbreviated arguments for these commands:

v - any real variable name fn - file name


str - string fid - file identifier
lt - linetype c - color

GENERAL

cd change directory
date returns date as day - month- year
demo run MATLAB demonstrations
dir list current directory contents
help returns list of general help categories
pause wait for the user to press any key
type fn list files in current directory
version list the MATLAB version
! execute operating system command

VARIABLES AND MEMORY

clear clear all variables and functions from memory


load fn retrieve variables stored on disk
save fn save workspace variables to disk
size(v) return dimensions of variable
who list current variables
whos list current variables with their size

INPUT AND OUTPUT

input (‘text’) prompt for user input


fclose (fid) close a file
fopen ('fn','permission') open a file, returns the file identifier
fscanf (fid, 'format', size) read a file
fprintf (fid, 'format', v) print to a file
MATH FUNCTIONS

All trigonometric functions work in radians. The function is applied element by element to
matrix arguments.

abs (v) absolute value


acos (v) inverse cosine
asin (v) inverse sine
atan (v) inverse tangent
ceil (v) round up towards positive infinity
conj (v) complex conjugate
cos (v) cosine
exp (v) exponential
fix (v) round toward zero
floor (v) round toward negative infinity
log (v) natural logarithm
log10 (v) common logarithm
pi 3.1415926535897...
round (v) round toward nearest integer
sin (v) sine
sqrt (v) square root
tan (v) tangent

MATRICES

det (v) determinant


diag (v) create or extract matrix diagonals
fliplr (v) flip matrix in the left/right direction
flipud (v) flip matrix in the up/down direction
inv (v) inverse
length(v) returns the length of vector v
lu (v) factors from Gausssian elimination
size(v) returns a vector [m,n] containing dimensions of v
ones(m,n) returns an m by n matrix filled with ones
v' transpose
[ v1 v2] augment matrix v1 with matrix v2; v1 and v2 must have the same number
of rows

DATA ANALYSIS

Each of these commands act upon the argument differently, depending on whether the
argument is a row vector or a matrix. If the argument is a row vector, the function acts
upon that row and returns one number. If the argument is a matrix, the function acts on
each column and returns a row vector.

max (v) largest component


mean (v) average or mean value
median (v) median value
min (v) smallest component
polyfit(x,y,n) returns vector of coefficients for nth order polynomial that fits x,y data
polyval(v,s) evaluates the polynomial represented by vector v at the value s
prod (v) product of elements
std (v) standard deviation
sum (v) sum of elements
trapz (v) numerical integration using trapezoidal rule

GRAPHICS - GENERAL

axis ([xmin xmax ymin ymax]) override auto-scaling of axes


axis(axis) freeze axis at current limits
axis('equal') make scaling in x and y directions equal
figure start a new graphics window
hold perform future graphics operations on current graph
pause(n) pause for n seconds before continuing
subplot (m, n, p) divide graphics window into m x n matrix with p
being the current matrix

GRAPHICS - 2D

bar (x, y) bar graph of elements in vector y at locations in vector x; values in


x must be evenly spaced and ascending
errorbar (x, y, e) creates xy plot with error bars ei long on either side of line; e must
be the same length as x and y
fill (x, y, 'c') fill a 2D polygon defined by points xiyi with color c
loglog (x, y, 'lt') log-log scale XY plot
fplot ('fun', limits) plot a MATLAB function between the x-axis limits = [xmin xmax]
plot(x, y, 'lt') create XY graph, auto-scaled unless followed by axis command
polar (theta, rho, 'lt') polar plot of angle theta (in radians) versus radius rho
semilogx (x, y, 'lt') semi-log scale XY plot (x axis)
semilogy (x, y, 'lt') semi-log scale XY plot (y-axis)
text (x, y, 'text') add text to a graph window; x and y are in current axis coordinates
title ('text') add a title to the current graph window
xlabel ('text') label the x-axis; substitute y or z for x for other axes
GRAPHICS - 3D

fill3 (x, y, z, 'c') same as fill command, but for polygons in 3D space
contour (x, y, Z, v) draw line contour plot of matrix Z using x and y for scaling; v
contains the values of the contour lines to be output
pcolor (x, y, Z) flooded color plot of matrix Z; use of shading interp recommended
mesh (x, y, Z) 3D meshed surface plot (wireframe)
meshc (x, y, Z) combine mesh plot with contour plot
surf (x, y, Z) 3D shaded surface plot

GRAPHICS - ANIMATION

getframe prepares the current figure as a pixel map


movie (M, n) play the movie stored in matrix M n times
moviein (k) prepare storage space for a movie with k frames

STRINGS

lower (str) convert string to lower case


num2str (v) convert a number to a string
str2num (str) convert a string to a number
strcmp (str1, str2) compares string 1 to string 2, returns 1 if identical, 0 if different
upper (str) convert string to upper case
[ str1 str2] concatenate string 1 and string 2
APPENDIX B
SAMPLE XYZ PLOTS
The following graphics examples were all produced by MATLAB and copied into this
document using the Edit..Copy command from the figure window. Each plot is a different
representation of the equation z = xe − x − y over the range of − 2 ≤ x ≤2 , − 2 ≤ y ≤3.
2 2

Example Contour Plot


3

2.5

1.5

0.5

-0.5

-1

-1.5

-2
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2

This contour plot was produced using the This is a surface plot using the
contour (x, y, Z, n) command with the value mesh (x, y, Z) command.
of n = 15.

This surface plot with projected line This plot is the same as the one above
contours was created using the except the panels are solid. It is
meshc (x, y, Z) command. produced by surf (x, y, Z).
APPENDIX C
SAMPLE Programs

Sample Program 1 Sample Program 2


%program PRESSURE % program Bounce
%calculates fluid pressure for range of depths % animates a bouncing ball

fprintf('Hi ... Welcome to MATLAB \n'); % create graphic "handle" for ball and trace
fprintf('CAD IS FUN \n');
depth = 0:1:10; % generate values of depth ball = plot(0,1,'r.','Markersize',100,'erasemode','xor');
g = 32.2; % assign acceleration hold on
constant trace = plot(0,1,'y.','erasemode','none');
rho = 1.94; % density of fluid axis([-1 16 -1 2]);
Pressure = rho * g * depth % the pressure for all depths axis('off'); % makes axis invisible
% the above line contains the pressures as a row vector
% to output results as a column take the transpose % use an exponential cosine function to generate
P = Pressure' % x and y position data for ball movement

PROGRAM OUTPUT for x=.1:.1:15


y = abs(exp(-x/10).*cos(x));
Hi ... Welcome to MATLAB drawnow
CAD IS FUN set(ball,'Xdata',x,'Ydata',y)
set(trace,'Xdata',x,'Ydata',y)
Pressure = end

Columns 1 through 7
PROGRAM OUTPUT (at program termination)
0 62.4680 124.9360 187.4040 249.8720 312.3400 374.8080

Columns 8 through 11

437.2760 499.7440 562.2120 624.6800

P=
0
62.4680
124.9360
187.4040
249.8720
312.3400
374.8080
437.2760
499.7440
562.2120
624.6800

Vous aimerez peut-être aussi