% Quick MATLAB Tutorial % Prepared for 605.721.71 Summer 2004 (June 5, 2004) % John E. Boon, Jr. % Resources used during preparation: % Coleman, Thomas F. and Van Loan, C., Handbook for Matrix Computations, % SIAM, 1988 (third printing 1991). % % The MathWorks, Inc.,MATLAB for MS-DOS Personal Computers, User's Guide, % October 15, 1990. % % MATLAB release 12, online Help, The MathWorks, Inc., 2000. echo on % General interface usage notes: % MATLAB is case sensitive. Any user-introduced name must start with % a letter but may contain special characters and numbers later. % First 19 characters of a user-introduced name are used by MATLAB. % non-MATLAB (operating system level) commands are accessed via ! % !whois jhu.edu % directory commands can be executed within MATLAB % cd matlab % dir % ls % to access MATLAB general help or help on a specific topic % help % help elmat % help short_MATLAB_tutorial % accesses the initial contiguous comments % short_MATLAB_tutorial % exeuctes this m file if it is in the default % MATLABPATH or added to MATLABPATH % commands ending in ; do not have their results displayed % otherwise, results are displayed immediately % multiple commands can be placed on a single line, each % separated by , % to clear the command window and its history use % clc % to clear the command window but retain history use % home % recursive functions can be created in MATLAB % echo off format short; % see format statements explained later % Create a string. Note use of single quotes s = 'hello' % text is stored as a vector, one character per vector element % to access the ASCII values of the characters in the string abs(s) % set vector to display as text instead of ACSII values setstr(s) % Create an m-by-n matrix % matrix_name = [ {row 1 elements 1..n} ; ... ; {row m elements 1..n} ] A = [1 2 3; 4 5 6; 7 8 9] % a vector is a one-dimensional array r = [10 11 12] % create an empty matrix D = [] % "Colon Method" for setting up row vectors v = 1:3 % v = { start} : { stop } v = 3:-1:0 % v = { start} : { increment } : { stop } v = 1:2:10 % v = { start} : { increment } : { stop } % scalars do not require [] x = pi % size of a matrix [m,n] = size(A) % length of a vector r_length = length(r) % checking on a matrix exist('D') isempty(D) % subscripting -- accessing subparts of a matrix A(1:2, 3) % first 2 rows of 3rd column of A A(2:3, 1:2) % last 2 rows and first 2 columns of A A(:, 3) % third column of A A(1:2,:) % first two rows of A % b=A(:) all of the elements of A are moved to a single column vector % A(:)=b if A exists, create a matrix with same dimensions as A but with % new contents from the righthand side % information on variables in use who % display all variables in use whos % space used by variables in use % removing variables clear r_length % removes a specific variable clear % removes all variables % entering complex numbers B = [1 2; 3 4] + i*[5 6; 7 8] C = [1+5*i 2+6*i; 3+7*i 4+8*i] % save a matrix to your default directory save C.mat C % show that matrix C is stored in file C.mat in directory dir % load matrices from disk load C.mat C A=[1 2 3; 4 5 6; 7 8 0]; % transpose a matrix B=A' % add matrices C = A + B x = [-1 0 2]'; % addition and subtraction defined if one operand is a scalar y = x - 1 % matrix multiplications examples x' * y y * x' % matrix-vector products b = A*x % matrix division X = A\B % is a solution to A*x=B X = B/A % is a solution to x*A=B % matrix powers A^3 % raise A to the 3rd power; A must be square, exponent a scalar x = 1:3; y = 4:6; % Pointwise operations (element-by-element) z = x.*y %z(i,j) = x(i,j)y(i,j) z = x.\y %z(i,j) = x(i,j)/y(i,j) % machine precision eps % smallest floating point number suc that if x=1+eps then x>1 % IEEE floating point results 1/0 % produces warning and Inf as result Inf/Inf % results in NaN 0/0 % produces warning and NaN as result % output format %format short %format long %format hex %format + help in displaying large matrices; (pos, neg, blank) entries % relational operators % < less than % <= less than or equal % > greater than % >= gretater than or equal % == equal % ~= not equal % logical operators % & and % | or % ~ not % any(x) returns 1 if any of the elements of the 0-1 vector are non-zero % all(A) returns 1 if all of the elements of A are non-zero % LU factorization % square matrices % express as the product of two triangular matrices, one of them a permutation % of the lower triangular matrix and the other an upper triangular matrix [L,U] = lu(A) % check that L*U produces A D = L*U % QR factorization % square and rectangular matrices % express the matrix as the product of an orthonormal matrix and an % upper triangular matri [Q,R] = qr(A) % singular value decomposition [U,S,V] = svd(A) % eigenvectors and eigenvalues [X,D] = eig(A) %invert a matrix, finds its determinate inv(A) det(A) % Programming control flow in MATLAB % FOR loops % for {var} = {row of vector counter values} % {statements} % end % example: n = 10; for i=1:n, x(i) = 0; end, x % example: m = 10; for i=1:m for j=1:n A(i,j)=1/(i+j-1); end end A % WHILE loops % while {relation} % {statements} % end % example: What is the first integer n for which n! is a 100 digit number? n=1; while prod(1:n) < 1.e100, n=n+1; end n % IF statements % if {relation} % {statements} % end % example: suppose n is a positive integer and want to set E to the upper % triangular matrix that has 1's on the diagonal and -1's above the % diagonal n = 5; for i=1:n for j=1:n if (ij) E(i,j) = 0; else E(i,j) = 1; end end end % Break command % used to terminate a loop % Example: print all Fibonacci numbers less than 1000 fib(1) = 1; fib(2) = 1; for j = 3:1000 z = fib(j-1) + fib(j-2); if z >= 1000 break end fib(j) = z; end fib % getting user input % gives prompt in the text string, waits, then returns the number or % expression input from the keyboard % user_entry = input('prompt') % displays prompt as a prompt on the screen, waits for input from the % keyboard, and returns the value entered in user_entry. % user_entry = input('prompt','s') % returns the entered string as a text variable rather than as a variable % name or numerical value n = input('Enter a number: ') % keyboard % when placed in an M-file, stops execution of the file and gives control % to the keyboard. The special status is indicated by a K appearing before % the prompt. You can examine or change variables; all MATLAB commands % are valid. This keyboard mode is useful for debugging your M-files. % To terminate the keyboard mode, type the command: % return % then press the Return key. % pause % by itself, causes M-files to stop and wait for you to press any key before % continuing. % pause(n) % pauses execution for n seconds before continuing, where n can be any real % number. The resolution of the clock is platform specific. A fractional % pause of 0.01 seconds should be supported on most platforms. % pause on % allows subsequent pause commands to pause execution. % pause off % ensures that any subsequent pause or pause(n) statements do not pause % execution. This allows normally interactive scripts to run unattended.