Chapter MATLAB Basis Learning Objectives:. Write simple program modules to implement single numerical methods and algorithms. Use variables, operators, and control structures to implement simple sequential algorithms Topics/Outline:. Arrays. Load and Save. Disp and fprintf..m-files 5. Plotting Chapter M: MATLAB Basis
Variables and Arrays The fundamental unit of data in MATLAB program is the array (Vector or Matrix) Even single value variables (Scalars) All operations are optimized for vector use Loops run slower in MATLAB than in Fortran (not a vector operation) size command gives size of the matrix Scalars, Vectors, Matrices MATLAB treat variables as arrays (matrices) Matrix (m n) - a set of numbers arranged in rows (m) and columns (n) Scalar: matrix Row Vector: n matrix Column Vector: m matrix A 5. 7 B 5.. 7. 5. C B'. 7. D. 5. 7. 5 9. 5 Chapter M: MATLAB Basis
Array: Data Organized into rows and columns Row Row Row A(,5) Row Col Col Col Col Col 5 Col 6 MATLAB Arrays Arrays fundamental unit of data 5. A 5. 5 5 matrix A = [,,-.5,,;,,.5,-,5]; Optional, use if it helps readability (comma) Start new row (semicolon) Suppress display (semicolon) Chapter M: MATLAB Basis
Data types All numbers are double precision The numerical values can be real, imaginary (i or j), or complex Text is stored as arrays of characters You don t have to declare the type of data (defined when running) MATLAB is case-sensitive!!! var = -.; var = i; var = -j; var =.5+.i; var5 = sqrt(.5); string = This is a character string String = Please enter your NetID Variable Names Usually, the name is identified with the problem Variable names may consist of up to 6 characters Variable names may be alphabetic, digits, and the underscore character ( _ ) Variable names must start with a letter ABC, A, C56, CVEN_, email_address day, year, iteration, max time, velocity, distance, area, density, pressure Time, TIME, time (case sensitive!!) Chapter M: MATLAB Basis
Initializing Variables Explicitly list the values reads from a data file uses the colon (:) operator reads from the keyboard A = [; ; 5; ]; B = [ 5; -6 -] C = [ 5 ; (continuation) -; 5 -] E = [A; ; A]; F = [C(,); A] Matrix Concatenation z x u v ; y 7 9 x y 7 9 x ; y 7 9 x y ; y x 7 7 9 9 Chapter M: MATLAB Basis 5
Chapter M: MATLAB Basis 6 E 5 C Colon Operator Creating new matrices (extracting subarrays) from an existing matrix C = [,,5; -,,;,,-;,,] E = C(:,:) = [- ; -] Colon Operator Creating new matrices from an existing matrix C = [,,5; -,,;,,-;,,] G 5 C G = C(:,:) = [,;,]
The end Function In array operations, end returns the highest value of a subscript C = [ 5; - ; -; ] H = C(:end,:end) = [ ; ] C 5 H Colon Operator Use subarrays on the LHS of a matrix Update elements of the existing array C = [ 5; - ; -; ] C([ ],:) = [ ; 5 6] C 5 C 5 6 Chapter M: MATLAB Basis 7
Chapter M: MATLAB Basis 8 Colon Operator Variable_name = first:incr:last time =.:.5:.5 time = [.,.5,.,.5,.,.5] values = :-: values = [, 9, 8, 7, 6, 5,,, ] linspace gives evenly spaced values x = linspace(,5); y = linspace(-pi,pi) x = linspace(a,b,n_pts) Special Matrices ones(,) ones() zeros(,) eye() Built-in MATLAB functions: zeros, ones, eye
Multidimensional Arrays» A(:,:,)=[ -5 7; 9 -];» A(:,:,)=[- 6; - 6];» A A(:,:,) = -5 7 9 - A(:,:,) = - 6-6» whos A Name Size Bytes Class A xx 96 double array Grand total is elements using 96 bytes MATLAB allocates array elements in column major order. A(,,),A(,,),A(,,),A(,,),A(,,),A(,,), A(,,),A(,,),A(,,),A(,,),A(,,),A(,,) Predefined Special Values The predefined values may be used any time in MATLAB without initializing them first Function Purpose pi (=.596558979) i, j (imaginary part of a complex number) Inf Machine infinity (divided by ) NaN Not-a-Number. Undefined mathematical operation. clock (year, month, day, hour, minute, second) date day-month-year, such as -Jan- eps epsilon, smallest difference between two numbers that can be represented on the computer ans store the result of unassigned variables Chapter M: MATLAB Basis 9
>> pi ans =.6 >> size(pi) ans = >> a=[ ; 5 6] a = 5 6 >> size(a) ans = pi.6 a= a 5 6 MATLAB Example» x=+5-. x = 7.8» y=*x^+5 y = 87.5» z=x*sqrt(y) z = 6.86» A=[ ; 5 6] A = 5 6» b=[;;5] b = 5» C=A*b C = 5» who Your variables are: A b y C x z» whos Name Size Bytes Class A x 8 double array C x 6 double array b x double array x x 8 double array y x 8 double array z x 8 double array» save Saving to: matlab.mat» save matrix default filename filename matrix Chapter M: MATLAB Basis
Initializing Variables with Keypad Input It is possible to prompt a user and initialize a variable with data input at the keyboard Name = input( Enter your name:, s ) SID = input( Enter your student ID: ) Tel = input( Telephone number: ) Cell = input( Cell phone number: ) Email = input( Email address:, s ) Input may be a value or a character string Array Operations An array operation is performed element-by-element C() A()* B(); C() A()* B(); C() A()* B(); C() A()* B(); C(5) A(5)* B(5); MATLAB: C = A.*B; Dot-operator works for.*,./,.^ Not needed for +, - Chapter M: MATLAB Basis
Element-by-Element Operations Symbol Operation Form Example Scalar-array addition AB [, 6] [ 7, 9] Scalar-array subtraction AB [ 8, ] 6 [, ] Array addition AB [, 6] [ 8, ] [, 9] Array subtraction AB [, 6] [ 8, ] [, ].* Array multiplication A.* B [, 6].*[, ] [ 6, 8]./ Array right division A. / B [, 7]. / [ 8, 5] [ / 8, 7 / 5].\ Array left division A.\ B [, 7]. \ [ 8, 5] [ \ 8, 7 \ 5].^ Array exponentiation A.^ B [, ].^ [ ^, ^ ] [ 6, 8].^[, 5] [ ^, ^ 5] [ 9, ] [ 5, ].^[, ] [ 5 ^, ^ ] [ 5, 8] Hierarchy of Arithmetic Operations. Parentheses, starting with the innermost pair. Exponentiation, from left to right. Multiplication and division with equal precedence, from left to right. Addition and subtraction with equal precedence, from left to right >> distance =.5 * accel * time^ >> distance =.5 * accel *(time^) >> distance = (.5 * accel * time)^ distance = distance distance Chapter M: MATLAB Basis
Chapter M: MATLAB Basis But a*b gives an error (undefined) because dimensions are incorrect. Need to use.* Vector and Matrix operations 7 b a 6 b 5 a 5* 6 * * a.* b Vectorized Matrix Operations 9 8 ).^ B ( F 5 7 8 A.^ E.5.6.75 B / A. D B A.* C 5 B 8 A
Array Operations for m n Matrices A : ; - : - : -; - 5 B A.* 5 5 5 5 8 C A.^ 8 7 5 5 7 7 8 5 6 6 Matrix Multiplications Recall how matrix multiplication works a d b e g c h f i j ag bh ci k dg eh fi l aj bk cl dj ek fl g h i j a k d l b e ga jd c ha kd f ia ld gb je hb ke ib le gc jf hc kf ic lf [A]*[B] [B]*[A] Chapter M: MATLAB Basis
Matrix Multiplication Matrix multiplication can be performed only if the inner dimensions are equal MATLAB In Fortran, the matrix multiplication has to be done by Do Loops In MATLAB, it is automatic A*B = C Note no period (not element-by-element operation) For vectors A*x = b Chapter M: MATLAB Basis 5
Chapter M: MATLAB Basis 6 Matrix Transpose ) ( )( ) ( ) )( ( - y' x * 6 9 6 8 x'* y - y' ; x' y ; x Built-in Functions Use help elfun for a list of elementary math functions All the standard operators +, -, *, /, ^ sin, cos, exp, tanh, log, log, etc. These operators are vectorized exp() exp(5) exp() exp(a) ; sin() sin(5) sin() sin( a ) ; 5 a
Common MATLAB Built-in Mathematical Functions abs(x) sin(x), cos(x), tan(x) asin(x), acos(x), atan(x), atan(y,x) angle(x) phase angle of complex x exp(x) sqrt(x) log(x), log(x) mod(x,y) remainder or modulo function [value,index] = max(x) [value,index] = min(x) Common MATLAB Built-in Rounding Functions ceil(x) rounds x to the nearest integer towards + fix(x) rounds x to the nearest integer towards floor(x) rounds x to the nearest integer towards round(x) rounds x to the nearest integer ceil(7.6) = 8, ceil(-7.6) = -7 fix(7.6) = 7, fix(-7.6) = -7 floor(7.6) = 7, floor(-7.6) = -8 round(7,6) = 7, round(-7.6) = -7 Chapter M: MATLAB Basis 7
Common MATLAB Built-in String Conversion Functions char(x) convert a matrix of numbers into a character string double(x) convert a character string into a matrix of numbers intstr(x) covert x into an integer character string numstr(x) convert x into a character string strnum(x) converts character sting s into a numeric array» string = 'Texas'; double(string) ans = 8 97 5» x=[8 97 5]; char(x) ans = Texas» intstr('tamu Civil') ans = 8 65 77 85 67 5 8 5 8 See Table in Appendix A for ASCII character set MAT Files Data Files memory efficient binary format preferable for internal use by MATLAB program ASCII files in ASCII characters useful if the data is to be shared (imported or exported to other programs) ASCII American Standard Code for Information Interchange Chapter M: MATLAB Basis 8
MATLAB Input To read files in if the file is an ascii table, use load if the file is ascii but not a table, file I/O needs fopen and fclose Reading in data from file using fopen depends on type of data (binary or text) Default data type is binary Save Files 8-digit text format (variable list) save <fname> <vlist> -ascii 6-digit text format save <fname> <vlist> -ascii -double Delimit elements with tabs save <fname> <vlist> -ascii -double -tabs Example: Vel = [ 5; -6 -] save velocity.dat Vel -ascii.e+.e+ 5.e+ -6.e+.e+ -.e+ Chapter M: MATLAB Basis 9
Load Files Read velocity into a matrix velocity.dat >> load velocity.dat >> velocity velocity = 5-6 -.e+.e+ 5.e+ -6.e+.e+ -.e+ Load Files Create an ASCII file temperature.dat % Time Temperature. 75..5 7.. 7.6.5 7.8. 79..5 8. read Time and Temperature from temp.dat >> load temperature.dat >> temperature Note: temperature is a 6 matrix Chapter M: MATLAB Basis
MATLAB Output Matlab automatically prints the results of any calculation (unless suppressed by semicolon ;) Use disp to print out text to screen disp (x.*y) disp ( Temperature = ) sprintf - display combination Make a string to print to the screen output = sprintf( Pi is equal to %f, pi) MATLAB Output numstr: convert a number to a string intstr: convert an integer to a string (round the element to integer)» string = ['The value of Pi = ' numstr(pi)];» disp (string) The value of Pi =.6» string = ['Value of sqrt(.5) ~ ' intstr(sqrt(.5))];» disp (string) Value of sqrt(.5) ~ Chapter M: MATLAB Basis
Formatted Output fprintf (format-string, var,.) %[flags] [width] [.precision] type Examples of type fields %d display value as an integer %e display in exponential format %f display in floating point or decimal notation %g display using %e or %f, depending on which is shorter %% display % \n skip to a new line Numeric Display Format MATLAB Command Display Example format short default.6 format long decimals.596558979 format bank decimals. format short e decimals.6e format long e 5 decimals.596558979e format,,blank x = [5 - -]; format + x = [+ - + + -] (+/- sign only) (blank for ) Chapter M: MATLAB Basis
fprintf( ) of Scalar temp = 98.6; fprintf( The temperature is %8.f degrees F.\n, temp); The temperature is 98.6 degrees F. fprintf( The temperature is %8.f degrees F.\n, temp); The temperature is 98.6 degrees F. fprintf( The temperature is %8.e degrees F.\n, temp); The temperature is 9.86e+ degrees F. fprintf( ) of Scalar speed =.; fprintf( The speed is %8.f m/s. \n, speed); Save at least 8 characters with decimal digits The speed is. m/s. speed = 59.5; fprintf( The speed is %6.f cm/s. \n, speed); Save at least 6 characters with decimal digits The speed is 59. cm/s. Chapter M: MATLAB Basis
fprintf( ) of Matrices score = [ ; 75 88 9; 99 8 95 5] fprintf( Game %d score: Houston: %d Dallas: %d \n, score) Game score: Houston: 75 Dallas: 99 Game score: Houston: 88 Dallas: 8 Game score: Houston: Dallas: 95 Game score: Houston: 9 Dallas: 5 M-Files You can create and save code in text files using MATLAB Editor/Debugger or other text editors (called m-files since the ending must be.m) Use % to add comments These files are called programs. They are similar to FORTRAN or C source codes. A script can be executed by typing the file name, or using the run command MATLAB executes everything stored in a.m file one line after the other as if the commands were entered in the command window Chapter M: MATLAB Basis