Lab

advertisement
Math 220
Prof. Diamond
Laboratory Notes 1
Note: MATLAB commands will be in boldface below.
First, find the My Documents folder and open it. When you have your own
programs to work on you will usually drag these programs into the My
Documents folder from your floppy disk.
Next, find MATLAB and open it. Generally there will be an icon on the
desktop you can double-click. You may need to look for it yourself
though – the name of the program is matlab.exe.
When you open MATLAB what you see is the command window.
*******************************************************
The working directory: This is where MATLAB will save programs (Mfiles) that you write, and where it looks first for programs that you
call from the command window and from other programs.
>>pwd
This will display the working directory. Usually you will want it to be
the My Documents folder. There are two ways to set this as the working
directory. The command
>>cd C:\MYDOCU~1
should do the job. If this doesn’t work use Set Path from the file menu
and type C:\My Documents in the current directory slot.
******************************************************
The help files:
There is extensive online help available.
From the command window, you can type
>>help fun
MATLAB will display information on the function named fun. For instance
type >>help plot for information on the plot command, >>help if for
information on the if statement, and >>help help for information on the
help statement itself. This is the best way to go if you know the name
of a function and need to be reminded of the syntax and/or options.
(Important note: All MATLAB built-in functions have lower-case names.
You can define your own functions with upper or lower case letters.
MATLAB is case-sensitive.)
There is also the help window, accessible through the help menu.
Very complete documentation, including tutorials and reference manuals,
is available through the help desk, which works through the browser
(Netscape or Explorer). Try it out
*************************************************************
The diary command:
You can keep a record of your MATLAB commands using the diary command.
You type
>>diary on
and MATLAB will open a text file named diary that will start recording
(or appending, if the file already exists) your MATLAB commands and
output.
>>diary off
will close the file. You can retrieve it from the My Documents folder.
Do >>help diary for more info.
******************************************************************
MATLAB operations and functions
The matrix ops tutorial begins by showing how to set up matrices.
The colon operation is very simple but useful in various settings. Here
we use it to pick out submatrices:
A(3,:) will pick out the third row of the matrix A
A(:,3) will pick out the third colum of A
A(2:5,:) will pick out rows 2 thru 5 of the matrix A
The end command is occasionally useful in dealing with matrices.
A(3:end) will give you from the third to the last entry in the (row or
column) vector A.
Matrix operations: Matrix multiplication is *, addition is + and
subtraction is - . Writing A^3 will take the third power of the matrix
A (and A needs to be a square matrix) A^(-1) gives the inverse of A if
A is square; inv(A) also gives the inverse. There is a special matrix
“division” operation called the slash operator, used to denote the
solution of a linear system. The symbol A\b is the solution x of the
linear system Ax=b. See help slash for more information.
***********************************************
Vectorized functions: The basic datatype in MATLAB is a matrix, and
almost all functions are designed to operate on matrices, usually (but
not always) by operating on each element of the matrix individually.
For instance, if
x=[1 3 2.5 3.1] then
sin(x)=[sin(1) sin(3) sin(2.5) sin(3.1)]. The usual arithmetic
operations of multiplication and division can be done element by
element on matrices by using the so-called array operators .* , and
./ . There is also term-by-term exponentiation, using the array
operator .^ .
So for instance, set:
x=[2 5 6 7]
y=[-1 4 3 2]
Then
x.*y=[-2 20 18 14]
x./y=[-2 5/4 6/3 7/2]
x.^2=[4 25 36 49]
x.^y=[2^(-1) 5^4 6^3 7^2]
These operations are very handy and allow for very compact coding of
functions/programs. It would be very tedious and very slow as well to
implement these operations in the standard way with “for” loops.
Incidentally, in the interests of speed and efficiency you should avoid
use of loops whenever possible and use built-in MATLAB functions
instead.
*******************************************************
Plotting in two dimensions
MATLAB can plot in two or three dimensions. We’ll mostly only need 2-D
plots. Plotting is done with the plot command. Do help plot for more
info and check the online help as well.
The basic MATLAB curve plot is plot(x,y) where x and y are onedimensional matrixes. MATLAB plots the points (x(1),y(1)),(x(2),y(2)),…
and connects them with straight lines. Axes and scaling are
automatically computed and can be manually adjusted if desired. There
are many options available. You can make multiple plots:
plot(x1,y1,x2,y2,x3,y3) will put three curves on the graph. If you make
a plot then you can add more plots to the same graph by the command
hold on . (otherwise each new plot will erase the old plot) You can
open a new plot window with the command figure . For a quick example,
you can try
x=0:.01:7;
plot(x,sin(x),x,sin(2*x));
This will plot sinx and sin2x on the same figure.
**************************************************
Loops and conditional statements
See Section 6 of MATLAB Primer for information on for, while, if
statements and for relational and logical operators. The for statement
looks like:
for t=A
statements
end
If you want to fit this, or some other sequence of statements, on one
line you can use commas or semicolons; in this case you could write
for t=A, statements; end;
Note that A is a specific matrix (or expression); what happens is that
the variable t is in turn successively set equal to each column of the
matrix A and then the statements are executed. Most often A is simply a
list of indices specified with the colon operator of the form a:b:c .
Example:
n=10;s=0; for i=1:n, s=s+i^2;end;
The above will find the sum of the squares of the numbers from 1 to 10.
The if and while statements are fairly standard in their form and
execution.
*******************************************************
M-files
There are two types of M files, referred to as script files and
function files. These files have the suffix .m, automatically appended
when you save them.
A script file is simply a list of MATLAB commands that are saved in a
file. You can choose your own name; say its name is myscript.m . When
MATLAB encounters the command myscript (you don’t put the .m in) either
in the command window or in another script file, it simply executes the
statements in myscript in order just as if they had been typed in. In
writing any M-file one customarily places comment statements at the top
that explain the purpose and execution of the file. If you type
help myscript
in the MATLAB command window, it will display these comment statements.
In a function file you basically construct your own MATLAB function,
with input variables and output variables. In fact, the built-in MATLAB
functions are written as M-files and in many cases you can even look at
the code.
See Section 12 of MATLAB Primer for a helpful description of function
files.
The function file has the form
function [output variable list]=functionname(input variable list)
%comment statements
statements
An important thing to note is that none of the variables need to be
declared or specified – everything is a matrix/array and you don't have
to prespecify the dimensions of any input or output variable. Typically
within the function are statements that extract the dimension
information using the size command (for arrays of any dimension) or the
length command (for one dimensional arrays).
Note: MATLAB supports arrays with any number of dimensions, along with
the operations of addition and scalar multiplication and the usual
array operations .* , ./ , .^ (and some others, such as convolution).
So, for instance, you can define the array A with A(i,j,k)=i+j-k for,
say, i from 1 to 5, j from 1 to 7, and k from 1 to 3.
Here’s an example of a function: Suppose we have a polynomial p(x) of
degree n, specified through its coefficients arranged in a row vector
a, where p(x)=a(1)+a(2)x+…+a(n+1)x^n. We write a little function pofx
which takes an array x and coefficient vector a as input and produces
p(x) (which acts on each element of the array x) as output. The
algorithm is Horner's method.
function y=pofx(x,a)
%a is coefficient vector, a(1) is constant term
%pofx(x,a) is the value of the polynomial p(x)
n=length(a);
y=0; %alternate: y=zeros(size(x));
for k=n:-1:1
y=a(k)+y.*x
end
This function is useful for plotting polynomials since it can calculate
p(x) for all the x-coordinates in one shot.
The inline statement:
This statement allows you to define your own function. See help inline
for more information. Note the use of single quotes to identify
expressions and string names. Examples are:
f=inline(‘x.^2’,‘x’)
which defines the function f, of one argument, by f(x)=x.^2. Note that
the function f as defined can operator on any array, as is the case
with most other MATLAB function. This is a desirable feature, but not
necessary.
g=inline(‘x.^2-y.^2’,‘x’,‘y’)
This defines a function named g of two arguments. If we write g(2,3)
then MATLAB sets x=2 and y=3 and evaluated x.^2-y.^2 . Note that if we
instead switch the order of the arguments and define
g=inline(‘x.^2-y.^2’,‘y’,‘x’)
and write g(2,3) then MATLAB identifies the first argument as y and the
second as x so y=2 and x=3 will be used to evaluate x.^2-y.^2.
The feval statement: See help feval for more information.
The expression [y1,..,yk] = feval(f,x1,...,xn) means the same as
[y1,..,yk] = f(x1,...,xn) but use of feval allows the function name to
be an input argument. For instance the MATLAB statements
f=‘sin’
feval(f,pi/2)
gives the answer sin(pi/2)=1 , and if we define
g=inline(‘x.^2-y.^2’,‘x’,‘y’)
then feval(g,2,3) gives –5 as the answer.
Download