Você está na página 1de 6

MatLab: A Brief Manual

I. RUNNING MATLAB

On first entry the computer opens a window in which information can be entered from the keyboard (this is called the
command window), and displays the following prompt symbol:
>>
From this point on, you type in individual MatLab commands
immediately following the program prompt. They will be processed when you hit the return key. Before you start it is
worth noting that the help facility in MatLab is particularly
good. If ever you dont know what to do you can often find
the answer by typing help functionname at the prompt.
A.

Variables

A MatLab variable can be represented by any combination


of letters and/or numbers. They are case sensitive. So, the
variables x and y are distinct from X and Y . Variables can be
either real or complex. By default, both i and j are initially
equal to the square root of . 1/. The equality sign is used to
assign values to variables:
>> x = 3
x =
3
>> y = x^2
y =
9
Note that output can be suppressed by putting a semicolon
(;) on the end of the command line.
>> y = x^2;
>> y
y =
9
At any time you want to know what variables have been defined, you can use who:
>> who
Your variables are:
x y
Some of the most important built-in constants and special
variables are
ans
Default name for results
eps Smallest number for which 1 C eps > 1
inf
Infinity
NaN
Not a number
p
i or j
1
pi

realmin
Smallest usable positive number
realmax
Largest usable positive number

B.

Arrays

Arrays can be created in several ways. One of them is to


type the elements of the array between brackets. The elements
in each row must be separated by blanks or commas. Here is
an example of generating a 3  3 matrix:
>> A = [ 2 -1 0
-1 2 -1
0 -1 1]
A =
2 -1 0
-1 2 -1
0 -1 1
The elements can also be typed on a single line, separating
the rows with semicolons:
>> A = [2 -1 0; -1 2 -1; 0 -1 1]
A =
2 -1 0
-1 2 -1
0 -1 1
The elements of a matrix, such as
2
3
A11 A12 A13
6
7
A D 4 A21 A22 A23 5
A31 A32 A33
can be accessed with the statement A(i,j), where i and j are
the row and column numbers, respectively. A section of an
array can be extracted by the use of colon notation. Here is an
illustration:
>> A =
A =
8
3
4

[8 1 6; 3 5 7; 4 9 2]
1 6
5 7
9 2

>> A(2,3) % Element in row 2, column 3


ans =
7
>> A(:,2) % Second column
ans =
1
5
9
>> A(2:3,2:3) % The 2 x 2 submatrix in lower
right corner
ans =
5 7
9 2

2
C.

Variable Arithmetic

All arithmetic is done to double precision, which means to


about 16 decimal digits of accuracy. Results can be displayed
in a shorter or a longer form. (Note: more than one command
may be entered on a single line, if they are separated by commas.)
>> a = sqrt(2);
>> format long, a
a =
1.41421356237310
>> format short, a
a =
1.4142
MatLab uses standard notation. Powers are performed before division and multiplication, which are done before subtraction and addition.
>> 3*4, 4^2
>> 2+3*4^2
ans =
50.

These matrix operations apply to scalars (1-by-1 matrices)


as well. If the sizes of the matrices are incompatible for the
matrix operation, an error message will result, except in the
case of scalar-matrix operations in which case each entry of
the matrix is operated on by the scalar.

A. Matrix Transpose

The transpose of a matrix is the result of interchanging rows


and columns. MatLab denotes the transpose by following the
matrix with the single-quote (apostrophe).
>> A
ans =
1 10 7
2 5 8
3 6 9
>> B =
B =
1.0000
2.0000
3.0000

[1+i, 2 + 2*i, 3 - 3*i]


- 1.0000i
- 2.0000i
+ 3.0000i

D. Command-line Editing
B. Matrix Addition and Subtraction

The arrow keys allow "command-line editing," which cuts


down on the amount of typing required, and allows easy error
correction . Press the "up" arrow, and add /2. What will this
produce?
>> 2+3*4^2/2
ans =
26
Parentheses may be used to group terms, or to make them
more readable. Press the "up" arrow again, and add parentheses thus:
>> (2 + 3*4^2)/2
ans =
25

Let matrix A have m rows and n columns, and B have p


rows and q columns. The matrix sum A C B is defined only
when m D p and n D q. The result is a n-by-m matrix having
the element-by-element sum of each of the components in A
and B.
>> E = [ 2 3; 4 5.0; 6 7];
>> F = [ 1 -2; 3 6.5; 10 -45];
>> E+F
ans =
3.0000 1.0000
7.0000 11.5000
16.0000 -38.0000

C. Matrix Multiplication

II. MATRIX OPERATIONS

The following matrix operations are available in MatLab:


Operator Description Operator Description
+
addition

transpose
subtraction
\
left division
*
multiplication
/
right division
^
power
If a and b are scalars, the right division a/b results in a divided by b, whereas the left division is equivalent to b/a. In
the case where A and B are matrices, B/A returns the solution
of X*A = B and A\B yields the solution of A*X = B.

Matrix multiplication requires that the sizes match. If they


dont, an error message is generated.
>>
>>
>>
>>

A*B, B*A;
B*A, A*B;
E*E, E*E;
E*F, E*F, F*E;

Scalars multiply matrices as expected, and matrices may be


added in the usual way (both are done element by element):
>> 2*A, A/4;
>> A + [B; B; B];

3
D. Rounding Floating Point Numbers to Integers

Functions which do this are round, fix, ceil, and floor. Here
are examples of these.
>>
>>
>>
>>
>>

F = [-.5 .1 .5];
round(F)
fix(F)
ceil(F)
floor(F)

Note that = is used in an assignment statement while == is


used in a relation. Relations may be connected or quantified
by the logical operators
Operator Description Operator Description
&
and
|
or
~
not
When applied to scalars, a relation is actually the scalar 1
or 0 depending on whether the relation is true or false (indeed,
you should think of 1 as true and 0 as false).

E. Element-by-element Operations

The operations of addition and subtraction operate on an


element-by-element basis, but other operations do not they
are matrix operations. MatLab has a convention in which a dot
in front of the operators: *, ^, \, and /, will force them
to perform element -by-element instead of the usual matrix
operation.
>> [1,2,3,4].*[1,2,3,4] (or)
>> [1,2,3,4].^2
ans =
1 4 9 16

F. Colon Notation

A central part of the MatLab language syntax is the "colon


operator," which produces a list.
>> -3:3
ans =
-3 -2 -1 0 1 2 3
The default increment is by 1, but that can be changed. For
example:
>> x = -3 : .3 : 3
x =
Columns 1 through 7
-3.0000 -2.7000 -2.4000 -2.1000 -1.8000 -1.5000 -1.2000
Columns 8 through 14
-0.9000 -0.6000 -0.3000 0 0.3000 0.6000 0.9000
Columns 15 through 21
1.2000 1.5000 1.8000 2.1000 2.4000 2.7000 3.0000

>> 3 < 5
ans =
1
>> a = 3 == 5
a =
0
When logical operators are applied to matrices of the same
size, their relation is a matrix of 0s and 1s giving the value of
the relation between corresponding entries.
>> A = [ 1 2; 3 4 ];
>> B = [ 6 7; 8 9 ];
>> A == B
ans =
0 0
0 0
>> A < B
ans =
1 1
1 1
To see how the other logical operators work, you should
also try
>>
>>
>>
>>
>>

~A
A&B
A & ~B
A|B
A |~A

IV. FLOW CONTROL

III. COMPARISON AND LOGICAL OPERATORS

MatLab provides several means for branching a programs


control of flow.

The comparison (relational) operators return 1 for true and


0 for false. These operators are

A. If-end

The most basic construction is:


Operator
Description
Operator
Description
<
less than
>
greater than
if <condition>,
<=
less than or equal to
>=
greater than or equal to
<program>
end
==
equal to
~=
not equal to

4
Here the condition is a logical expression that will evaluate
to either true or false (i.e., with values 1 or 0). When it evaluates to 0, the program control moves on to the next part of
the program. You should keep in mind that MatLab regards
expressions like (A DD B) and (A <D B) as functions with
values 0 or 1.
>> a = 1;
>> b = 2;
>> if a < b, c = 3; end;
>> c
c =
3

B.

If-else-end

Frequently, this construction is elaborated with


if <condition>,
<program1>
else
<program2>
end

>> for i = 1 : 5, c = 2*i, end


c =
2
.....
c =
10
FOR loops may be nested. In this example there are
two loops, with one nested inside the other. They define
A.1; 1/; A.1; 2/; A.1; 3/; : : : ; A.1; 10/; A.2; 1/; : : : ; A.10; 10/
in that order.
>> for i=1:10,
for j=1:10,
A(i,j) = i/j;
end
end
MatLab will allow you to put any vector in place of the list 1:n
in this construction. The following construction will execute
5 times and the values for the variable i during execution are
successively, 2,4,5,6,10.
>> for i = [2,4,5,6,10],
<program>,
end

In this case, if the condition is 1 program1 is executed, if 0


then program2 is executed.

B.

While Loop

A WHILE loop is a construction of the form


C. If-elseif-end

Another variation is
if <condition1>,
<program1>
elseif <condition2>,
<program2>
end
Now if condition1 is 1, then program1 is executed, if condition1 is 0 and if condition2 is 1, then program2 is executed,
and otherwise control is passed on to the next part of the program.

V.

>>while <condition>,
<program>,
end
where condition is a MatLab function, as with the branching
construction. The program program will execute as long as the
value of condition is not 0. WHILE loops carry an implicit
danger in that there is no guarantee in general that you will
exit a while loop.
C. break

Any loop can be terminated by the break statement. Upon


encountering a break statement, the control is passed to the
first statement outside the loop.

LOOPING CONSTRUCTIONS
D. continue
A. FOR Loops

A FOR loop is a construction of the form


for i= 1 : n,
<program>,
end
The program will repeat program once for each index value
i D 1; 2; : : : n. For example, these statements compute and
print c D 2  i for i D 1; 2; : : : ; 5.

When the continue statement is encountered in a loop, the


control is passed to the next iteration without executing the
statements in the current iteration.
E. return

A function normally returns to the calling program when it


runs out of statements. However, the function can be forced
to exit with the return command.

5
F. error

Execution of a program can be terminated and a message


displayed with the error function: error(message)
VI. SCRIPTING FILES
A. Program Development with m-files

MatLab statements can be written and stored in a file for


later use. Such a file is referred to as a script, or an mfile (since they must have a name extension of the form filename.m). Suppose you have created a script in the MatLab
language, stored in a file myfile.m. The commands in this file
can be exectued by simply giving the command
>> myfile
The statements will run like any other MatLab function. You
do not need to compile the program since MatLab is an interpretative (not compiled) language. An m-file can reference
other m-files, including referencing itself recursively. As an
example, using the editor, create the following file, named
sketch.m:
[x y] = meshgrid(-3:.1:3, -3:.1:3);
z = x.^2 - y.^2;
mesh(x,y,z);
Then, making sure you are in the directory containing this file,
enter
>> sketch
The result is the same as if you had entered the three lines of
the file, at the prompt.
B. Functions and Function Files

These allow you to create new problem-specific functions


having the same status as other built-in MatLab functions.
They are like scripts, but for the purposes of computational
speed, are compiled the first time. Example : Here we create
a file named sqroot.m containing the following lines.
function sqroot(x)
% SQROOT Compute square root by Newtons
method
% Initial guess
xstart = 1;
% Iteration loop to compute square root
for i = 1:100
xnew = ( xstart + x/xstart)/2;
disp(xnew);
if abs(xnew - xstart)/xnew < eps, break, end;
xstart = xnew;
end;
return;

The first line declares the function name, input arguments,


and output arguments; without this line the file would be a
script file. Notice that the file name corresponds to the function name. The first few lines of a function are comment statements so that they can be used in online-help. This is a good
habit to get into.
>> help sqroot
SQROOT Compute square root by Newtons method
With the m-file in place, we can call the function and the
square root of 20 will be computed.
>> format long
>> sqroot(20)
10.50000000000000
6.20238095238095
4.71347454528837
4.47831444547438
4.47214021706570
4.47213595500161
4.47213595499958
4.47213595499958
Example 2 : A function may have multiple output arguments. For example:
function [mean, stdev] = stat(x)
% STAT Mean and standard deviation
% For a vector x, stat(x) returns the
% mean and standard deviation of x.
% For a matrix x, stat(x) returns two row
% vectors containing,respectively, the mean
% and standard deviation of each column.
[m n] = size(x);
% handle case of a row vector
if m == 1, m = n; end
mean = sum(x)/m;
stdev = sqrt(sum(x.^ 2)/m - mean.^2);
return;
Notice that mean and stdev are both computed inside the function body. Once this is placed in the m-file stat.m, the following command will assign the mean and standard deviation of
the entries in the vector y to y m and yd respectively. For example, the script of code will show computation of the mean
and standard deviation of the integers one through ten.
>> y = [1:10];
>> [ym, yd] = stat(y)
ym =
5.5000
yd =
2.8723
Single assignments can also be made with a function having
multiple output arguments. For example, these statements will
assign the mean of y to y m.
>> ym = stat(y)
ym =
5.5000

6
VII.

GRAPHICS

Two- and three-dimensional MatLab graphs can be given


titles, have their axes labeled, and have text placed within the
graph. The basic functions are:

B. Three-dimensional Graphics :

Three dimensional plots are drawn using


Function

Function
Description
plot(x,y)
plot y vs x
plot(x,y1,x,y2,x,y3) plot y1, y2 and y3 vs x on same graph
xlabel(x axis label)
labels x axis
ylabel(y axis label)
labels y axis
title (title of plot)
puts a title on the plot
MatLab graphics windows will contain one plot by default.
The command subplot can be used to partition the screen so
that up to four plots can be viewed simultaneously. For more
information, type

plot3(x,y,z)

mesh(x,y,z)

>> help subplot


surf(x,y,z)
A.

Two-dimensional Plots

The plot command creates linear x-y plots; if x and y are


vectors of the same length, the command plot(x,y) opens a
graphics window and draws an x-y plot of the elements of x
versus the elements of y. Example : Lets draw the graph of
the sine function over the interval 4 to 4.
>>
>>
>>
>>

x = -4:.01:4; y = sin(x); plot(x,y)


grid
xlabel(x)
ylabel(sin(x))

The vector x is a set of values of x which divides the range


up into a meshsize of 0.01, while y is a vector giving the values of sine at these values (recall that sin operates entrywise).
Plots of parametrically defined curves can also be made. For
example,
>> t=0:.001:2*pi; x=cos(3*t); y=sin(2*t); plot(x,y)

In order to draw more than one plot on the same graph, use
the command hold. The command hold freezes the current
graphics screen so that subsequent plots are superimposed on
it. Entering hold again releases the hold. The commands
hold on and hold off are also available.
You can override the default linetypes and pointtypes. For
example, these commands render a dashed line and dotted line
for the first two graphs while for the third the symbol is placed
at each node.
>>
>>
>>
>>

x = 0:.01:2*pi; y1=sin(x); y2=sin(2*x); y3=sin(4*x);


plot(x,y1,--,x,y2,:,x,y3,+)
grid
title (Dashed line and dotted line graph,color,red)

The available line-and point-types are as follows. See help


plot for more information.
Linetypes
solid (-), dashed (), dotted (:), dashdot (-.)
Marktypes point (.), plus (+), star (*), circle (o), x-mark (x)

contour(z)

Description
Plots a line in 3-space through the points
whose coordinates are the elements of x, y
and z, where x, y and z are three vectors of
the same length.
Creates a three-dimensional perspective plot
of the elements of the matrix z. It is drawn like
a wire mesh, defined by the z-coordinates of
points above a rectangular grid in the
x-y plane.
Creates a three-dimensional perspective plot
of the elements of the matrix z. It is redrawn
as a continuous surface, defined by the
z-coordinates of points above a rectangular
grid in the x-y plane.
Creates a contour plot of matrix z treating the
values of z as heights above a rectangular grid
in the x-y plane.

To draw a line graph in a three-dimensional space you use


plot3 in exactly the same way as you use plot in twodimensions. For example the following will draw helix.
>>
>>
>>
>>

z = 0:pi/50:10*pi;
x = sin(z);
y = cos(z);
plot3(x,y,z)

To draw a surface plot of the function z D f .x; y/ over a


rectangle, you first define vectors xx and yy, which give partitions of the sides of the rectangle. With the function meshgrid you then create a matrix x, each row of which equals xx
and whose column length is the length of yy, and similarly a
matrix y, each column of which equals yy. For example:
>> xx = -3:.1:3;
>> yy = -3:.1:3;
>> [x,y] = meshgrid(xx,yy);
You then compute a matrix z, obtained by evaluating f entrywise over the matrices x and y, to which mesh can be applied. Example : You can draw a graph of over the square
2; 2  2; 2 as
>>
>>
>>
>>

z = x.^2 - y.^2;
mesh(z)
surf(x,y,z)
contour(x,y,z)

Consult help plot3, help mesh, help surf, help contour, for
more information.

Você também pode gostar