Вы находитесь на странице: 1из 82

MatLab Workshop

DAY 1

MATLAB, which stands for MATrix LABoratory, is a product of The Mathworks, Inc.

MATLAB is a platform independent (meaning it should work equally well on a PC, a MAC, or a mainframe system), interactive environment for computation, visualization, and animation.

MATLAB has a natural language interface that is easy to use. It also has built-in functions and toolboxes that help facilitate problem solution and graphical visualization of problems.

MATLAB is especially powerful in the solution of linear algebra (matrix) problems. Remember It is Case Sensitive.

What Is MATLAB?
MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easyto-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include Math and computation Algorithm development Data acquisition Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientech and engineering graphics Application development, including graphical user interface building

What does it look like?

Most Important Matlab Command:Help


a long list of help topics for which on-line help is Available >> help >> helpwin -- open help window and show default help topics >> helpdesk -- open first page of help window >> demo -- open list of available demo in matlab We can also obtain information about a particular function or command, for example >> help sqrt or >> lookfor sqrt

Quitting & interrupting MATLAB


Type quit in command window or use menus: File, Exit Matlab To interrupt: Use ctrl-C

Scalar, Vector, and Matrices


Matlab works with a rectangular numerical matrix All variables represent matrices!!! 1. Scalars: 1-by-1 matrices

Scalar, Vector, and Matrices


1. Scalars: 1-by-1 matrices 2. Vectors: matrices with only one row or one column

Scalar, Vector, and Matrices


1. Scalars: 1-by-1 matrices 2. Vectors: matrices with only one row OR one column 3. Matrices Entered by an explicit list of elements. For example, A = [1 2 3; 4 5 6; 7 8 9]

Entering data
Matrices can be entered in several dierent ways: Enter an explicit list of elements. Load matrices from external data les. Generate matrices using built-in functions. Create matrices with your own functions in M-les.

Entering data
To enter a matrix explicitly, simply type in the Command Window >> A = [1 2 3; 4 5 6; 7 8 9] MATLAB display the matrix you just entered: A= 123 456 789

Subscripts
The element in row i and column j of A is denoted by A(i,j). Typing >> A(1,3) + A(3,2) will give the result ans = 11

Dimensions
If you assign a value to a position that is out of the range of the matrix, MATLAB increases the size automatically. >> X = A; >> X(3,4) = 10 X= 1230 4560 7 8 9 10

Colon operator
The colon : is one of the most important MATLAB operators. For example the expression >> 1:10 is a row vector containing the integers from 1 to 10: ans = 1 2 3 4 5 6 7 8 9 10 To obtain non unit spacing, specify an increment: >> 15:-2.5:5 ans = 15 12.5 10 7.5 5

Colon operator
Subscript expressions involving colons refer to portions of a matrix: >> A(1:k,j) is the first k elements of the j-th column of A. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. >> A(:,end) represents the last column vector of A: ans = 3 6 9

Effort should be made to become familiar with them!!!

Colon operator
1:5 0.4:0.2:1.2 A(1:4,3) A(:,3) A(1:4,:) A(:, [2 4]) = [ ] A(:, [2 4]) = B(:,1:2) [1 2 3 4 5] [0.4,0.6,0.8,1.0,1.2] The column vector with the first four entries of the third column The third column of A The first four rows of A Delete columns 2 and 4 of A Replacing columns 2,4 with the first two columns of B

Generated by built-in functions


>> eye
EYE(N) is the N-by-N identity matrix. EYE(M,N) or EYE([M,N]) is an M-by-N matrix with 1's on the diagonal and zeros elsewhere. EYE(SIZE(A)) is the same size as A. EYE with no arguments is the scalar 1. EYE(M,N,CLASSNAME) or EYE([M,N],CLASSNAME) is an M-by-N matrix with 1's of class CLASSNAME on the diagonal and zeros elsewhere.

Example: x = eye(2,3,'int8');

Generated by built-in functions. For example,

>> zeros
ZEROS(N) is an N-by-N matrix of zeros. ZEROS(M,N) or ZEROS([M,N]) is an M-by-N matrix of zeros. ZEROS(M,N,P,...) or ZEROS([M N P ...]) is an M-by-N-by-P-by-... array of zeros. ZEROS(SIZE(A)) is the same size as A and all zeros. ZEROS with no arguments is the scalar 0. ZEROS(M,N,...,CLASSNAME) or ZEROS([M,N,...],CLASSNAME) is an M-by-N-by-... array of zeros of class CLASSNAME. Example: x = zeros(2,3,'int8');

Generated by built-in functions. For example,

>> ones
ONES(N) is an N-by-N matrix of ones. ONES(M,N) or ONES([M,N]) is an M-by-N matrix of ones.

ONES(M,N,P,...) or ONES([M N P ...]) is an M-by-N-by-P-by-... array of ones.


ONES(SIZE(A)) is the same size as A and all ones.

ONES with no arguments is the scalar 1.


ONES(M,N,...,CLASSNAME) or ONES([M,N,...],CLASSNAME) is an M-by-N-by-... array of ones of class CLASSNAME. Example: x = ones(2,3,'int8');

Generated by built-in functions. For example,

>> linspace
LINSPACE Linearly spaced vector. LINSPACE(X1, X2) generates a row vector of 100 linearly equally spaced points between X1 and X2. LINSPACE(X1, X2, N) generates N points between X1 and X2. For N < 2, LINSPACE returns X2.

Class support for inputs X1,X2: float: double, single

Generated by built-in functions. For example,

>> rand
RAND Uniformly distributed random numbers. RAND(N) is an N-by-N matrix with random entries, chosen from a uniform distribution on the interval (0.0,1.0). RAND(M,N) and RAND([M,N]) are M-by-N matrices with random entries. RAND(M,N,P,...) or RAND([M,N,P,...]) generate random arrays. RAND with no arguments is a scalar whose value changes each time it is referenced. RAND(SIZE(A)) is the same size as A.

Generated by built-in functions. For example,

>> randn
RANDN(N) is an N-by-N matrix with random entries, chosen from a normal distribution with mean zero, variance one and standard deviation one.

RANDN produces pseudo-random numbers. The sequence of numbers generated is determined by the state of the generator. Since MATLAB resets the state at start-up, the sequence of numbers generated will be the same unless the state is changed. S = RANDN('state') is a 2-element vector containing the current state of the normal generator. RANDN('state',S) resets the state to S. RANDN('state',0) resets the generator to its initial state. RANDN('state',J), for integer J, resets the generator to its J-th state. RANDN('state',sum(100*clock)) resets it to a different state each time

Generated by built-in functions. For example,

>> diag
DIAG Diagonal matrices and diagonals of a matrix. DIAG(V,K) when V is a vector with N components is a square matrix of order N+ABS(K) with the elements of V on the K-th diagonal. K = 0 is the main diagonal, K > 0 is above the main diagonal and K < 0 is below the main diagonal. DIAG(V) is the same as DIAG(V,0) and puts V on the main diagonal. DIAG(X,K) when X is a matrix is a column vector formed from the elements of the K-th diagonal of X. DIAG(X) is the main diagonal of X. DIAG(DIAG(X)) is a diagonal matrix. Example m = 5; diag(-m:m) + diag(ones(2*m,1),1) + diag(ones(2*m,1),-1) produces a tridiagonal matrix of order 2*m+1.

Generated by built-in functions. For example,

>> diag
E.g >> diag(1:5,0) ans = 1 0 0 0 2 0 0 0 3 0 0 0 0 0 0
A= 1 2 3 4 5 6 7 8 9 >> diag(A) ans = 1 5 9

0 0 0 4 0

0 0 0 0 5

Generated by built-in functions. For example,

>> blkdiag
Construct a block diagonal matrix from input arguments
>> blkdiag(A,A) ans = 1 4 7 0 0 0 2 5 8 0 0 0 3 6 9 0 0 0 0 0 0 1 4 7 0 0 0 2 5 8 0 0 0 3 6 9

Generated by built-in functions. For example,

>> magic Magic square.


MAGIC(N) is an N-by-N matrix constructed from the integers 1 through N^2 with equal row, column, and diagonal sums. Produces valid magic squares for all N > 0 except N = 2. Construct a block diagonal matrix from input arguments >> A = magic(3) A= 8 3 4 1 5 9 6 7 2

Expressions
Like most other programming languages, MATLAB provides mathematical ex-pressions, but unlike most programming languages, these expressions involve entire matrices. The building blocks of expressions are
Varibales Numbers Operators Functions

Variables
MATLAB does not require any type declarations or dimension statements. >> num_students = 25 creates a 1-by-1 matrix named num_students and stores the value 25 in its element. Variable names consist of a letter, followed by any number of letters, digits, or underscores. MATLAB is case sensitive

Parentheses ()
Parentheses are used to indicate precedence in arithmetic expressions and to enclose arguments of functions in the usual way. X(3) is the third element of X. X([1 2 3]) is the first three elements of X. If X has N components, X(N:-1:1) reverses them. X(X>0.5) returns those elements of X that are > 0.5.

Braces{}
Braces are used to form cell arrays. X{3} is the contents of the third element of X. X{3}(4,5) is the (4,5) element of those contents. X{[1 2 3])} is a comma-separated list of the first three elements of X. It is the same as X{1},X{2},X{3}

[ ] Brackets
Brackets are used in forming vectors and matrices
[6.9 9.64 sqrt(-1)] is a vector with three elements separated by blanks. [6.9, 9.64, sqrt(-1)] is the same thing. [1+i 2-i 3] and [1 +i 2 -i 3] are not the same. [11 12 13; 21 22 23] is a 2-by-3 matrix. A = [] stores an empty matrix in A.

Values of Useful Constants


pi = 3.14159265 . . . i = Imaginary unit,1 j = Same as i eps =Floating-point relative precision, e = 252 realmin =Smallest oating-point number, 21022 realmax =Largest oating-point number, (2 e)1023 Inf = Innity NaN = Not-a-number

who(s), clear, save


>>Who This shows all active variables. Try the command whos

who(s), clear, save


>>Who This shows all active variables. Try the command whos >>clear a b This removes the variables a and b >>clear all This remove all variables

who(s), clear, save


>>save filename This creates a le filename.mat which contains all variables >>save filename x y z This creates a le filename.mat which contains variables x y z >>clc Clear command prompt window

Operators
Expressions use familiar arithmetic operators and precedence rules. + Addition - Subtraction * Multiplication / Division \ Left Division ^ Power Complex conjugate transpose ( ) Specify evaluation order

Pointwise Operation
+ addition subtraction . Element-by-element multiplication . b Element-by-element power . \ Element-by-element left division ./ Element-by-element right division . Unconjugate array transpose (same as transpose(A)

Pointwise Operation: Some Examples


Matlab Command Output [1,2,3].*[5,6,7] [5,12,21] [10:-2:0]. ^ 2 [100,64,36,16,4,0] 2. ^ [1:6] [2,4,8,16,32,64] [2,4,6]./ 2 [1,2,3] 2./ [2,4,6] [1.000 0.5000 0.3333] [2,2,2]./ [2,4,6] [1.000 0.5000 0.3333] [2,4,6] . \ 2 [1.000 0.5000 0.3333] [1 1+2*i; i 3]. 1.0000 0+1.0000i 1.0000+2.0000i 3.0000

Lets practice
See the output on your screen >> a = [1, 3, 5, 7, 9] or >> a= [1 3 5 7 9]

Lets practice
See the output on your screen >> a=1:2:9 or >> a=[1:2:9]

Lets practice
See the output on your screen >> a = linspace(1,5,7) >> v = linspace(-10,10,500); >> length(v) or >> size(v)

Lets practice
See the output on your screen >> a = [1 3 5]; >> b = [2 4 6]; Then >> c = [a b]

Lets practice
See the output on your screen >> A=[1 2 3 4]; B= [2 1 0 4] >> C = A+B; >> A = A-B; >> D = A' >> A*A' >> A'*A >> V = [1 2 3] >> A*V >> c = A+100; >> c-50

Lets practice
See the output on your screen >> A=1:4; >> log(A) >> sqrt(A) Construct a vector x containing 8 values, starting with 0 and ending with . Next construct a vector y which contains sine of the entries of the vector x. What is the sum of the 4th elements of x and y.

Lets practice
See the output on your screen >> v = [-7 3 5]; >>sum(v) = 1 [adds elements of v] >>max(v)=3 [gives the maximum element] >>abs(v)=[7 3 5] >>sort(-v)= [-5 -3 7] [sorts in increasing order] >> median(v)=3 [gives median of the elements] >> mean(v)=0.3333 [gives mean of the elements] >> std(v)=6.4291 [gives the standard deviation]

Lets practice
See the output on your screen >> a = [2 4 6]; b = [1 -3 2]; >> a*b >> a.*b >> a./b >> a.^2 >> a.^b

Lets practice
See the output on your screen Create a vector x from 1 to 4 with four elements and a vector y from 4 to -3 with step size -2. Find [max(b.^a) min(b.^a)]. Find sin(a.*b). Create a vector v containing integers from 10 to 100. How can you create a vector w containing elements which are reciprocals of the corresponding elements of v. What do you expect the outcome of following command line to be? >> v=[1 4 16 25]; z = (sqrt(v)).^2

Functions
MATLAB provides a large number of standard elementary mathematical functions, including abs, sqrt, exp, and sin. For a list of the elementary mathematical functions, type >> help elfun For a list of more advanced mathematical and matrix functions, type >> help specfun >> help elmat

Math Functions
The Matlab command help elfun gives a list of elementary math functions

Trigonometric: sin, sinh, asin, asinh, cos, cosh, acos, acosh, tan, tanh, atan, atan2, atanh, sec, sech, asech, csc, csch, acsc, acsch, cot, coth, acot, acoth

Math Functions
The Matlab command help elfun gives a list of elementary math functions

Expotential: exp, log, log10, log2, pow2, sqrt, nextpow2

Math Functions
The Matlab command help elfun gives a list of elementary math functions

Complex: abs, angle, complex, conj, imag, real, unwrap, isreal, cplxpair

Math Functions
The Matlab command help elfun gives a list of elementary math functions

Rounding and remainder: fix, floor, ceil, round, rem, sign

Hardcopy
The Matlab command >>diary lename causes what appears subsequently on the screen (except graphics) to be written to the named diskle (if no le is specied, the le diary is used). To save space, dont forget the command >>format compact The Matlab command >>diary off suspends diary The Matlab command >>diary on turns diary back on

Format Functions
format format short format long Default. Same as short Fixed point with 5 decimal places Fixed point with 15 decimal places format short e Floating point with 5 decimal places format long e Floating point with 15 decimal places format short g Best of xed or oating point with 5 DPs format long g Best of xed or oating point with 15 DPs format hex Hexadecimal format format compact Suppress extra line-feeds format loose Put the extra line-feeds back in Try the example t = [4/3 1.2345e-6]

Format Functions
>> x = [4/3 1.2345e-6] >> format short x= 1.3333 0.0000 >> format short e x= 1.3333e+000 1.2345e-006 >> format short g x= 1.3333 1.2345e-006 >> format long x= 1.33333333333333 0.00000123450000 >> format rat x= 4/3 1/810045

M-les
Files that contain code in the Matlab language are called M-les. You create M-les using a text editor The name of each M-le must end in .m and must be found on MATLABs search path.

M-les
There are two kinds of M-les Scripts: do not accept input arguments or return arguments. They operate on data in the workspace

M-les
There are two kinds of M-les Scripts: do not accept input arguments or return arguments. They operate on data in the workspace Functions: accept input arguments and return output arguments. Internal variables are local to the function

Scripts
A script may contain any sequence of MATLAB statements, including references to other M-les. For example, create a le called magicrank.m that contains these Matlab commands: % Investigate the rank of magic squares r = zeros(1,14); for n = 3:14 r(n) = rank(magic(n)); end r bar(r)

Scripts
To invoke the script magicrank.m, just type the statement magicrank This causes execution of the commands in magicrank. That is, ranks of the rst 14 magic squares are computed and bar graph of the result is plotted variables n and r remain in the workspace

Functions
Functions are M-les that can accept input arguments and return output arguments.

Functions
Functions are M-les that can accept input arguments and return output arguments. The names of the M-le and of the function should be the same.

Functions
Functions are M-les that can accept input arguments and return output arguments. The names of the M-le and of the function should be the same. Functions operate on variables within their own workspaces.

Functions
Functions are M-les that can accept input arguments and return output arguments. The names of the M-le and of the function should be the same. Functions operate on variables within their own workspaces. You can create M-les using the built-in Matlab text editor, or any other text editor.

Functions: Exercise
Write a function called mytridiag that takes as input n, and returns the n n tridiagonal matrix that has the pattern suggested by 2 1 0 0 1 4 1 0 0 1 6 1 0 0 1 8

Functions: Exercise
Write a function called mytridiag that takes as input n, and returns the n n tridiagonal matrix that has the pattern suggested by 2 1 0 0 1 4 1 0 0 1 6 1 0 0 1 8

Functions: Exercise
Use the built-in Matlab editor to create a le called mytridiag.m Here is the rst line of the le function [A] = mytridiag(n) This says that function mytridiag takes only one input argument which has been given the dummy name n, and returns only one output argument, whose dummy name is A. The second line is the H1 (help 1) line. It should start with the comment symbol,%, followed without any space by the function name in capital letters, followed by one or more spaces, and then a brief description, followed by a blank line.

Functions: Exercise
Here is the le mytridiag.m function [A] = mytridiag(n) % MYTRIDIAG(n) creates an nxn tridiagonal % matrix with 2,4,...,2n on main diagonal % and -1 on subdiagonal and superdiagonal A=diag(2*(1:n))+diag(-ones(1,n-1),1) ... +diag(-ones(1,n-1),-1);

Functions: Exercise
The function in our example has just one command line. The three red dots are the continuation symbol, used when one command doesnt t on one line. Type help mytridiag. What happens? Your function description should be brief but precise! Try your function with mytridiag(12)

Graphics
XY plots If we want to plot the graph of y = f(x) by hand, one way is Make a list of X-values, Compute corresponding Y-values Plot the point (x,y) and connect. MATLAB does exactly the same thing. The command >> plot(X,Y) produces a graph of the elements of vector X versus the corresponding elements of the vector Y.

Graphics
Creating a plot: plot x=0:pi/100:2*pi; y=sin(x); plot(x,y);

Graphics
>> x = linspace(-2,2,100); >> y1 = x./(1+x.^2); >> plot(x,y1) >> hold on [freezes the current graph window] >> y2 = (x.^2)./(1+x.^2); >> plot(x,y2) compare your output with others >> hold off [releases the hold

Graphics
Creating a plot: plot x=0:pi/100:2*pi; y=sin(x); plot(x,y); Multiple data sets on a graph x=0:pi/100:2*pi; y=sin(x); y1=sin(x-0.25); y2=sin(x-0.5); plot(x,y,x,y1,x,y2); legend(sin(x),sin(x-0.25),sin(x-0.5));

Graphics
Multiple plots in one gure: subplot(m,n,p) subplot(2,2,1); plot(x,y); subplot(2,2,2); plot(x,y1); subplot(2,2,3); plot(x,y2); subplot(2,2,4); plot(x,y1+y2);

Graphics
Axis labels and titles: xlabel,ylabel,title,text >>plot(x,y); axis([0,2*pi,-1,1]); >>xlable(x is between 0 and 2pi); >>ylabel(y=sin(x)); >>title(Graph of the sine function); >>text(3, 0.5, y=sin(x)); >> grid on

Practice Graphics
Example Graph of r = 3 + 4cos The following set of commands >> theta = linspace(0,2*pi,100); >> r = 3 + 4*cos(theta); >> polar(theta,r)

Practice Graphics

Practice Graphics

Вам также может понравиться