User:Eml4500.f08.team.dwyer.jd/HW1

''' 7. Scalar Functions. '''

Certain Matlab functions operate on scalars, the most common functions are: sin       asin        exp               abs        round cos       acos        log               sprt       floor tan       atan        rem(remanider)    sign       ceil

''' 8. Vector Functions. '''

Some other Matlab functions operate essentially on a vector (row column), but act on an m-by-n matrix (m > 2) in a column fashion to produce a row vector containing the results of their application to each column. Row-by-row action can be obtained by using the transpose; for example, mean(A')'. A few of these functions are: max        sum        median      any min        prod       mean        all sort                  std For example, the maximum entry in a matrix A is given by max(max(A)) rather than max(A).

''' 9. Matrix Functions. '''

Much of MATLAB's power comes from its matrix functions. The most useful ones are:

eig    eigenvalues and eigenvectors chol   cholesky factoriztion svd    singular value decomposition inv    inverse lu     LU factoriztion qr     QR factoriztion hess   hessenburg form schur  schur decomposition rref   reduced row echelon expm   matrix exponential sqrtm  matrix exponential poly   characterisitc polynomial det    determinant size   size norm   1-norm, 2-norm, F-norm cond   condition number in the 2-norm rank   rank

''' 10. Command line editing and recall. '''

The command line in MATLAB can easily be edited by using the backspace (or delete) key. On a PC try the Home, End, and Delete keys; on Unix system or a PC the Emacs commands Ctl-a, Ctl-e, Ctl-d, and Ctl-k work; on othe systems see help cedit or type cedit. A convenient feature is use of the up/down arrows to scroll through the stack of previous commands. One can, therefore, recall a precious command line, edit it, and execute the revised command line.

11. Submatrices and colon notation.

Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects. Creative use of these features to vectorize operations permits one to minimize the use of loops (which slows MATLAB) and to make code simple and readable.

The expression 1:5 is actually the row vector [1 2 3 4 5]. The numbers need not be integers nor the increment one. For example,


 * 0.2:0.2:1.2

gives [0.2, 0.4, 0.6, 0.8, 1.0, 1.2], and


 * 5:-1:1 gives [5 4 3 2 1].

The colon notation can be used to access submatrices of a matrix. For example,


 * A(1:4,3) is the column vector consisting of the first four entries of the third column of A.

A colon by itself denotes an entire row or column:


 * A(:,3) is the third column of A; and A(1:4,:) is the first four rows.

Arbitrary integral vectors can be used as subscripts:


 * A(:,[2 4]) contains as columns, columns 2 and 4 of A.

Such subscripting can be used on both sides of an assignment statement:


 * A(:,[2 4 5]) = B(:,1:3) replaces columns 2,4,5 of A with the first three columns of B. Note that the entire altered matrix A is printed and assigned. Try it

''' 12. M-files. '''

M-files must have the file type ".m" which MATLAB uses to execute a sequence of statements stored in diskfiles.


 * There are two types of M-files: script files and function files.

Script files.

A script file consists of a sequence of normal MATLAB statements. If the file has the filename, say, rotate.m, then the MATLAB command rotate will cause the statements in the file to be executed. Variables in the script file are global and will change the value of variables of the same name in the environment of the current MATLAB session.

Script files may be used to enter data into a large matrix; in such a file, entry errors can be easily corrected. If, for example, on enters in a diskfile data.m


 * A = [

1 2 3 4 5 6 7 8 ];

then the MATLAB statement data will cause the assignment given in data.m to be carried out. However, it is usually easier to use the MATLAB function load (see section 2).


 * An M-file can reference other M-files, including referencing itself recursively.

Function files.

Function files provide extensibility to MATLAB. You can create new functions specific to your problem which will then have the same status as other MATLAB functions. Variables in a function file are by default local. A variable can, however, be declared global (see help global).


 * We first illustrate with a simple example of a function file.

function a = randint(m,n) %RANINT Ramdomly generated integral matrix. %   randint(m,n) returns and m-by-n such matrix with entries %   between 0 and 9. a = floor(10*rand(m,n));


 * A more general version of this function is the following:

function a = randint(m,n,a,b) %RANDINT Ramdomly generated integral matrix. %   randint(m,n) returns and m-by-n such matrix with entries %   between o and 9. %   rand(m,n,a,b) return entries between integers a and b.          if nargin < 3, a = 0; b = 9; end a = floor((b-a+1) * rand(m,n)) + a;

This should be placed in a diskfile with filename randint.m. The first line declares the function name, input arguments, and output arguments; without this line the file would be a script file.

Note that use of nargin ("number of input arguments") permits one to set a default value of an omitted input variable - such as a and b in the example.


 * A function may also 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 of x;          %    [mean, stdev] = stat(x) both the mean and standard deviation. %   For a matrix x, stat(x) acts colunmwise. [m n] = size(x); if m == 1 m =n; % handle case of a row vector end mean = sum(x)/m; stdev = sqrt(sum(x.^2/m - mean.^2);

Once this is placed in a diskfile stat.m, a MATLAB command [xm, xd] = stat(x), for example, will assign the mean and standard deviation of the entires in the vector x to xm and xd, respectively. No brackets needed for single assignments and will assign the mean of x to xm. The % symbol indicates the line is a comment.

If you can not vectorize some computation, you can make your for loops go faster by preallocating any vectors or matrices in which output is stored. For, example, by including the second statement below, which uses the function zeros, space for storing E in memory is preallocated. Without this MATLAB must resize E one column larger in each iteration, slowing execution. M = magic(6); E = zeros(6,50); for j = 1:50 E(:j) = eig(M^i); end

Some more advanced features are illustrated by the following function. As noted earlier, some of the input arguments of a function, such as tol in this example, may be made optional through use of nargin. The variable nargout can be similarly used. Note that the fact that a relation, "nonzero" means "true" and 0 means "false". Finally, the MATLAB function feval permits one to have as an input varible a string naming another function. (Also see eval) function [b,steps] = bisect(fun, x, tol) %Bisect zero of a function of one variable via the bisection method.

% Initialization if nargin < 3, tol = eps; end trace = (nargout == 2); if x ~= 0, dx = x/20; else, dx = 1/20; end a = x - dx; fa = feval(fun,a); b = x + dx; fb = feval(fun,b);

% Find change of sign. while (fa > 0) == (fb >0) dx = 2.0*d; a = x -dx; fa = feval(fun,b); end

% Main loop while abs(b - a) > 2.0*tol*max(abs(b),1.0) c = a + 0.5*(b - a); fc = feval(fun,c); if trace, steps = [steps; [c fc]]; end if (fb > 0) == (fc > -) b = c; fb = fc; else a = c; fa = fc; end end