Matlab Tutorial 1 - Lecture notes All the lecture PDF

Title Matlab Tutorial 1 - Lecture notes All the lecture
Course  Advanced Reactor Design
Institution Colorado State University
Pages 23
File Size 395.1 KB
File Type PDF
Total Downloads 109
Total Views 125

Summary

Matlab Tutorial 1 ...


Description

Matlab Summary and Tutorial

Matlab Summary and Tutorial Table of Contents Matlab Summary Matlab (matrix algebra) How to quit Matlab Batch jobs MATLAB Tutorial Building Matrices Variables Functions Relations and Logical Operations Colon Notation Miscellaneous Features Programming in MATLAB Assignment Branching For Loops While Loops Recursion Miscellaneous Programming Items Scripts Suggestions MATLAB demonstrations Some MATLAB built-in functions Some MATLAB function descriptions

Matlab Summary and Tutorial

MATLAB Summary MATLAB (matrix algebra) Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. It is a mainstay of the Mathematics Department software lineup and is also available for PC's and Macintoshes and may be found on the CIRCA VAXes. Matlab is well adapted to numerical experiments since the underlying algorithms for Matlab's builtin functions and supplied m-files are based on the standard libraries LINPACK and EISPACK. Matlab program and script files always have filenames ending with ".m"; the programming language is exceptionally straightforward since almost every data object is assumed to be an array. Graphical output is available to supplement numerical results. Online help is available from the Matlab prompt (a double arrow), both generally (listing all available commands): >> help [a long list of help topics follows]

and for specific commands: >> help fft [a help message on the fft function follows].

Paper documentation is on the document shelf in compact black books and locally generated tutorials are available and are used in courses.

How to quit Matlab The answer to the most popular question concerning any program is this: leave a Matlab session by typing quit

or by typing exit

to the Matlab prompt.

Batch jobs Matlab is most often used interactively, but "batch" or "background" jobs can be performed as well. Debug your commands interactively and store them in a file (`script.m', for example). To start a background session from your input file and to put the output and error messages into another file (`script.out', for example), enter this line at the system prompt: nice matlab < script.m >& script.out

&

You can then do other work at the machine or logout while Matlab grinds out your program. Here's an explanation of the sequence of commands above. 1. The "nice" command lowers matlab's priority so that interactive users have first crack at the CPU. You must do this for noninteractive Matlab sessions because of the load that number--crunching puts on the CPU. 2. The "< script.m" means that input is to be read from the file script.m. 3. The ">& script.out" is an instruction to send program output and error output to the file script.out. (It is important to include the first ampersand (&) so that error messages are sent to your file rather than to the screen -- if you omit the ampersand then your error messages may turn up on other people's screens and your popularity

Matlab Summary and Tutorial

will plummet.) 4. Finally, the concluding ampersand (&) puts the whole job into background. (Of course, the file names used above are not important -- these are just examples to illustrate the format of the command string.) A quick tutorial on Matlab is available in the next Info node in this file. (Touch the "n" key to go there now, or return to the menu in the Top node for this file.)

MATLAB Tutorial MATLAB Tutorial (based on work of R. Smith, November 1988 and later) This is an interactive introduction to MATLAB. I have provided a sequence of commands for you to type in. The designation RET means that you should type the "return" key; this is implicit after a command. To bring up MATLAB from from the operating system prompt lab%

you should type matlab lab% matlab RET

This will present the prompt >>

You are now in MATLAB. If you are using the X Window system on the Mathematics Department workstations then you can also start MATLAB from the Main Menu by selecting "matlab" from the "Math Applications" submenu. A window should pop up and start MATLAB. When you run MATLAB under the window system, whether you start from the menu or a system prompt, a small MATLAB logo window will pop up while the program is loading and disappear when MATLAB is ready to use. When you are ready to leave, type exit >> exit RET

In the course of the tutorial if you get stuck on what a command means type >> help RET

and then try the command again. You should record the outcome of the commands and experiments in a notebook. Remark: Depending on the Info reader you are using to navigate this tutorial, you might be able to cut and paste many of the examples directly into Matlab.

Building Matrices Matlab has many types of matrices which are built into the system. A 7 by 7 matrix with random entries is produced by typing

Matlab Summary and Tutorial

rand(7)

You can generate random matrices of other sizes and get help on the rand command within matlab: rand(2,5) help rand

Another special matrix, called a Hilbert matrix, is a standard example in numerical linear algebra. hilb(5) help hilb

A 5 by 5 magic square is given by the next command: magic(5) help magic

A magic square is a square matrix which has equal sums along all its rows and columns. We'll use matrix multiplication to check this property a bit later. Some of the standard matrices from linear algebra are easily produced: eye(6) zeros(4,7) ones(5)

You can also build matrices of your own with any entries that you may want. [1

2

3

5

7

9]

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

2 RET

3

4 RET 5

6]

[Note that if you are using cut-and-paste features of a window system or editor to copy these examples into Matlab then you should not use cut-and-paste and the last line above. Type it in by hand, touching the Return or Enter key where you see RET, and check to see whether the carriage returns make any difference in Matlab's output.] Matlab syntax is convenient for blocked matrices: [eye(2);zeros(2)] [eye(2);zeros(3)] [eye(2),ones(2,3)]

Did any of the last three examples produce error messages? What is the problem?

Variables Matlab has built-in variables like pi, eps , and ans. You can learn their values from the Matlab interpreter. pi

Matlab Summary and Tutorial

eps help eps

At any time you want to know the active variables you can use who: who help

who

The variable ans will keep track of the last output which was not assigned to another variable. magic(6) ans x = ans x = [x, eye(6)] x

Since you have created a new variable, x, it should appear as an active variable. who

To remove a variable, try this: clear x x who

Functions a = magic(4)

Take the transpose of a: a'

Note that if the matrix A has complex numbers as entries then the Matlab function taking A to A' will compute the transpose of the conjugate of A rather than the transpose of A. Other arithmetic operations are easy to perform. 3*a -a a+(-a) b = max(a) max(b)

Matlab Summary and Tutorial

Some Matlab functions can return more than one value. In the case of max the interpreter returns the maximum value and also the column index where the maximum value occurs. [m, i] = max(b) min(a) b = 2*ones(a) a*b a

We can use matrix multiplication to check the "magic" property of magic squares. A = magic(5) b = ones(5,1) A*b v = ones(1,5) v*A

Matlab has a convention in which a dot in front of an operation usually changes the operation. In the case of multiplication, a.*b will perform entry-by-entry multiplication instead of the usual matrix multiplication. a.*b

(there is a dot there!)

x = 5 x^2 a*a a^2 a.^2

(another dot)

a triu(a) tril(a) diag(a) diag(diag(a)) c=rand(4,5) size(c) [m,n] = size(c) m d=.5-c

There are many functions which we apply to scalars which Matlab can apply to both scalars and matrices. sin(d) exp(d) log(d) abs(d)

Matlab has functions to round floating point numbers to integers. These are round , fix , ceil, and floor . The next

Matlab Summary and Tutorial

few examples work through this set of commands and a couple more arithmetic operations. f=[-.5 .1 .5] round(f) fix(f) ceil(f) floor(f) sum(f) prod(f)

Relations and Logical Operations In this section you should think of 1 as "true" and 0 as "false." The notations &, |, ~ stand for "and,""or," and "not," respectively. The notation == is a check for equality. a=[1 0 1 0] b=[1

1

0

0]

a==b am an error message will be dished up. Here you can nest the conditions. if i = & | ~ abs all ans any acos asin atan atan2 axis

chol clc clear clg clock conj contour cos cumprod cumsum delete det diag diary dir

end eps error eval exist exit exp expm eye feval fft filter find finite fix

function global grid hess hold home ident if imag inf input inv isnan keyboard load

lu macro magic max memory mesh meta min nan nargin norm ones pack pause pi

quit qz rand rcond real relop rem return round save schur script semilogx semilogy setstr

sprintf sqrt startup string subplot sum svd tan text title type what while who xlabel

Matlab Summary and Tutorial

* \ / ^

balance break casesen ceil chdir

acosh angle asinh atanh bar bench bessel bessela besselh besseln blanks cdf2rdf census citoh cla compan computer cond conv conv2 corr cosh ctheorem dc2sc deconv addtwopi bartlett bilinear blackman boxcar

disp echo eig else elseif

demo demolist dft diff eigmovie ergo etime expm1 expm2 expm3 feval fft2 fftshift fitdemo fitfun flipx flipy funm gallery gamma getenv ginput gpp graphon hadamard buttap butter chebap chebwin cheby

floor flops for format fprintf hankel hds hilb hist histogram hp2647 humps idft ieee ifft ifft2 info inquire int2str invhilb isempty kron length log10 logm logspace matdemo matlab mean median

cov decimate denf detrend eqnerr2

fftdemo filtdemo fir1 fir2 freqs

log loglog logop ltifr ltitr

plot polar prod prtsc qr

membrane menu meshdemo meshdom mkpp movies nademo nelder neldstep nnls null num2str ode23 ode45 odedemo orth pinv plotdemo poly polyfit polyline polymark polyval polyvalm ppval freqz fstab hamming hanning interp

kaiser numf readme2 remez remezdd

shg sign sin size sort

ylabel zeros

print quad quaddemo quadstep rank rat ratmovie readme residue retro roots rot90 rratref rratrefmovie rref rsf2csf sc2dc sg100 sg200 sinh spline sqrtm square std sun

table1 table2 tanh tek tek4100 terminal toeplitz trace translate tril triu unmkpp vdpol versa vt100 vt240 why wow xterm zerodemo zeroin

specplot spectrum triang xcorr xcorr2 yulewalk

Some MATLAB function descriptions These lists are copied from the help screens for MATLAB Version 4.2c (dated Nov 23 1994). Only a few of the summaries are listed -- use Matlab's help function to see more. >> help HELP topics: matlab/general matlab/ops matlab/lang matlab/elmat matlab/specmat matlab/elfun matlab/specfun matlab/matfun matlab/datafun matlab/polyfun matlab/funfun matlab/sparfun matlab/plotxy matlab/plotxyz matlab/graphics matlab/color matlab/sounds matlab/strfun matlab/iofun matlab/demos toolbox/chem toolbox/control fdident/fdident fdident/fddemos toolbox/hispec toolbox/ident

-

General purpose commands. Operators and special characters. Language constructs and debugging. Elementary matrices and matrix manipulation. Specialized matrices. Elementary math functions. Specialized math functions. Matrix functions - numerical linear algebra. Data analysis and Fourier transform functions. Polynomial and interpolation functions. Function functions - nonlinear numerical methods. Sparse matrix functions. Two dimensional graphics. Three dimensional graphics. General purpose graphics functions. Color control and lighting model functions. Sound processing functions. Character string functions. Low-level file I/O functions. The MATLAB Expo and other demonstrations. Chemometrics Toolbox Control System Toolbox. Frequency Domain System Identification Toolbox Demonstrations for the FDIDENT Toolbox Hi-Spec Toolbox System Identification Toolbox.

Matlab Summary and Tutorial

toolbox/images toolbox/local toolbox/mmle3 mpc/mpccmds mpc/mpcdemos mutools/commands mutools/subs toolbox/ncd nnet/nnet nnet/nndemos toolbox/optim toolbox/robust toolbox/signal toolbox/splines toolbox/stats toolbox/symbolic toolbox/wavbox simulink/simulink simulink/blocks simulink/simdemos toolbox/codegen

- Image Processing Toolbox. - Local function library. - MMLE3 Identification Toolbox. - Model Predictive Control Toolbox - Model Predictive Control Toolbox - Mu-Analysis and Synthesis Toolbox.: Commands directory - Mu-Analysis and Synthesis Toolbox -- Supplement - Nonlinear Control Design Toolbox. - Neural Network Toolbox. - Neural Network Demonstrations and Applications. - Optimization Toolbox. - Robust Control Toolbox. - Signal Processing Toolbox. - Spline Toolbox. - Statistics Toolbox. - Symbolic Math Toolbox. - (No table of contents file) - SIMULINK model analysis and construction functions. - SIMULINK block library. - SIMULINK demonstrations and samples. - Real-Time Workshop

For more help on directory/topic, type "help topic". >> help elmat Elementary matrices and matrix manipulation. Elementary matrices. zeros - Zeros matrix. ones - Ones matrix. eye - Identity matrix. rand - Uniformly distributed random numbers. randn - Normally distributed random numbers. linspace - Linearly spaced vector. logspace - Logarithmically spaced vector. meshgrid - X and Y arrays for 3-D plots. : - Regularly spaced vector. Special variables and constants. ans - Most recent answer. eps - Floating point relative accuracy. realmax - Largest floating point number. realmin - Smallest positive floating point number. pi - 3.1415926535897.... i, j - Imaginary unit. inf - Infinity. NaN - Not-a-Number. flops - Count of floating point operations. nargin - Number of function input arguments. nargout - Number of function output arguments. computer - Computer type. isieee - True for computers with IEEE arithmetic. isstudent - True for the Student Edition. why - Succinct answer. version - MATLAB version number. Time and dates. clock cputime date etime tic, toc -

Wall clock. Elapsed CPU time. Calendar. Elapsed time function. Stopwatch timer functions.

Matrix manipulation. diag - Create or extract diagonals. fliplr - Flip matrix in the left/right direction. flipud - Flip matrix in the up/down direction. reshape - Change size. rot90 - Rotate matrix 90 degrees. tril - Extract lower triangular part. triu - Extract upper triangular part. : - Index into matrix, rearrange matrix. >> help specmat Specialized matrices. compan gallery

- Companion matrix. - Several small test matrices.

Matlab Summary and Tutorial

hadamard hankel hilb invhilb kron magic pascal rosser toeplitz vander wilkinson

-

Hadamard matrix. Hankel matrix. Hilbert matrix. Inverse Hilbert matrix. Kronecker tensor product. Magic square. Pascal matrix. Classic symmetric eigenvalue test problem. Toeplitz matrix. Vandermonde matrix. Wilkinson's eigenvalue test matrix.

>> help elfun Elementary math functions. Trigonometric. sin sinh asin asinh cos cosh acos acosh tan tanh atan atan2 atanh sec sech asec asech csc csch acsc acsch cot coth acot acoth -

Sine. Hyperbolic sine. Inverse sine. Inverse hyperbolic sine. Cosine. Hyperbolic cosine. Inverse cosine. Inverse hyperbolic cosine. Tangent. Hyperbolic tangent. Inverse tangent. Four quadrant inverse tangent. Inverse hyperbolic tangent. Secant. Hyperbolic secant. Inverse secant. Inverse hyperbolic secant. Cosecant. Hyperbolic cosecant. Inverse cosecant. Inverse hyperbolic cosecant. Cotangent. Hyperbolic cotangent. Inverse cotangent. Inverse hyperbolic cotangent.

Exponential. exp log log10 sqrt

-

Exponential. Natural logarithm. Common logarithm. Square root.

Complex. abs angle conj imag real

-

Absolute value. Phase angle. Complex conjugate. Complex imaginary part. Complex real part.

Numeric. fix floor ceil round rem sign

-

Round towards zero. Round towards minus infinity. Round towards plus infinity. Round towards nearest integer. Remainder after division. Signum function.

>> help specfun Specialized math functions. besselj bessely besseli besselk beta betainc betaln ellipj ellipke erf erfc erfcx

-

Bessel function of the first kind. Bessel function of the second kind. Modified Bessel function of the first kind. Modified Bessel function of the second kind. Beta function. Incomplete beta function. Logarithm of beta function. Jacobi elliptic functions. Complete elliptic integral. Error function. Complementary error function. Scaled complementary error function.

Matlab Summary and Tutorial

erfinv expint gamma gcd gammainc lcm legendre gammaln log2 pow2 rat rats cart2sph cart2pol pol2cart sph2cart

-

Inverse error function. Exponential integral function. Gamma function. Greatest common divisor. Incomplete gamma function. Least common multiple. Associated Legendre function. Logarithm of gamma function. Dissect floating point numbers. Scale floating point numbers. Rational approximation. Rational output. Transform from Cartesian to spherical coordinates. Transform from Cartesian to polar coordinates. Transform from polar to Cartesian coordinates. Transform from spherical to Cartesian coordinates.

>> help matfun Matrix functions - numerical linear algebra. Matrix analysis. cond - Matrix condition number. norm - Matrix or vector norm. rcond - LINPACK reciprocal condition estimator. rank - Number of linearly independent rows or columns. det - Determinant. trace - Sum of diagonal elements. null - Null space. orth - Orthogonalization. rref - Reduced row echelon form. Linear equations. \ and / - Linear equation solution; use "help slash". chol - Cholesky factorization. lu - Factors from Gaussian elimination. inv - Matrix inverse. qr - Orthogonal-triangular decomposition. qrdelete - Delete a column from the QR factorization. qrinsert - Insert a column in the QR factorization. nnls - Non-negative least-squares. pinv - Pseudoinverse. lscov - Least squares in the presence of known covariance. Eigenvalues and singular values. eig - Eigenvalues and eigenvectors. poly - Characteristic polynomial. polyeig - Polynomial eigenvalue problem. hess - Hessenberg form. qz - Generalized eigenvalues. rsf2csf - Real block diagonal form to complex diagonal form. cdf2rdf - Complex diagonal form to real block diagonal form. schur - Schur decomposition. balance - Diagonal scaling to improve eigenvalue accuracy. svd - Singular value decomposition. Matrix functions. expm - Matrix exponential. expm1 - M-file implementation of expm. expm2 - Matrix exponential via Taylor series. expm3 - Matrix exponential via eigenvalues and eigenvectors. logm - Matrix logarithm. sqrtm - Matrix square root. funm - Evaluate general matrix function. >> help general General purpose commands. MATLAB Toolbox Version 4.2a 25-Jul-94 Managing commands and functions. help - On-line documentation. doc - Load hypertext documentation. what - Directory listing of M-, MAT- and MEX-files. type - List M-file. lookfor - Keyword search through the HELP entries. wh...


Similar Free PDFs