Lecture Notes 11-19-09 ENGR 0011 - Dr. Lund What we ve learned so far About the MATLAB environment Command Window Workspace Window Current Directory Window History Window How to enter calculations (and suppress output with ;) How to use variable names Basic mathematical functions in MATLAB How to enter and manipulate arrays in MATLAB How to perform matrix operations versus element-by-element array operations ( + - * ) versus ( + -.*./.^ ) How to enter and manipulate arrays in MATLAB (Section 4.6) What We Will Learn Today Getting program input using load and input commands Loading external data (Section 4.8) Getting input from program user (Section 4.11.3) Creating MATLAB programs in script (.m) files Program processing structures: If Statements (Section 4.10.3) Loops (Section 4.10.4) Using MATLAB to solve Simultaneous Linear Equations (Section 4.11) NOTE: The material presented in these lecture notes does not Program output summary completely follow in the same order as the book. It is presented to facilitate completing Assignment 11 Loading Data from External Files Command: load filename.txt What does this command do? Loads data from filename.txt into an array variable called filename Data file must be an ASCII text file 1
Different Ways of Loading Data Files What if we had a different data file name? How can we use the load command differently such that we only have to modify one line if the file name is different? load ( lineq.dat ) How can we capture the result of this command? system = load ( lineq.dat ) What happens if we assign the name of a data file as a string to a variable? filename = lineq.dat Can the variable filename be used in the load command? YES: system = load(filename) Creating and Running Script Files Save your script as filename.m in your current directory note change of extension You have just created a MATLAB script In the MATLAB command window, type» filename How to allow your program to run with any user-entered file name Create a data file (.dat or.txt) which contains the A matrix and b vector for a system of equations, where data is stored such that the A and b matrices are next to each other, i.e. the first row contains the first row of the A matrix and the first element of the b vector. The number of rows will therefore be the same as the number or unknowns for the system of equation, and the number of columns will be one greater than the number of rows How would you load this data file? filename=input( Enter file name:, s ); system = load(filename) 2
Separating Data Use of COLON (:) in array extraction With the data loaded and stored to the variable system (or whatever variable name you choose), how would you obtain A and b? For a system of 3 equations A = system ( :, 1:3 ) This translates to extracting all of the rows in columns 1-3 b = system ( :, 4 ) This translates to extracting all of the rows in column 4 How to allow your program to run with any size data file How could you modify a MATLAB program to be able to determine if data from file was stored horizontally or vertically? By determining the number of rows vs. number of columns MATLAB Command: size(matrix) What does size(lineq) give you? How many outputs are there? What are the outputs How can we assign the outputs to variables? [rows, cols] = size(system) Obtaining Input from User In Matlab, command is: input To acquire numerical input AGE = input ( How old are you? ) To acquire string (text) input MONTH = input ( What is your name?, s ) Notice additional argument ( s ) required for string input 3
Summary Input Statements input var_no = input( What? ); var_str = input( What?, s ); load load dataset.txt loads data from a text file and assigns to variable called dataset filename = input( Type in data file, s ) data = load(filename) - assigns data from text file to variable called data The use of the : argument to define variables Using MATLAB to Solve Ax=b Given the following equations, how would you represent them as a linear system of equations: 3x + 5z = 2y z = 2y 8 4(x + y) = 2(0.5 - z) How would you represent these equations in matrix form, A*x = b? 3 2 5 x 0 A 0 2 1 x y b 8 4 4 2 z 1 Why? (i.e. what do you get when you multiply A*x?) 3x 2y + 5z = 0 0x + 2y - z = 8 4x + 4y + 2z = 1 Using MATLAB to Solve Ax=b How do you solve a linear system of equations in MATLAB? Matrix Operations A * x = b A -1 * A * x = A -1 * b I * x = A -1 *b x = A -1 * b MATLAB Command: inv(a) Test the following What is inv(a) * A? Let I = inv(a)*a What s I * b? What does that prove? 4
Using MATLAB to Solve Ax=b What if data file was loaded vertically, i.e. such that all the x coefficients were in first row, y coefficients in second row, z coefficients in third row, and b vector in fourth row? MATLAB transpose command: A Atrans = system ( 1:rows 1, : ) A = Atrans brow = system ( rows, : ) b = brow 3 A 0 4 2 2 4 5 3 1 A' 2 2 5 Transposing 0 2 1 4 4 2 Using MATLAB to Solve Ax=b Create M-file which loads program, determines if system of equations is stored horizontally or vertically, then determine A, b, x accordingly if (cols-rows) == 1 A = lineq ( :, 1:cols-1 ) b = lineq( :, cols ) x = inv(a) * b elseif (rows-cols) == 1 Atrans = lineq ( 1:rows-1, : ) A = Atrans' btrans = lineq ( rows, : ) b = b' x = inv(a) * b else disp('error in data set') Program Branching: If Statements Branching gives a program the ability to make decisions based on specified data or user input A program makes the decisions using relational and logical operations Relational operators: < <= > >= ~= == Logical operators: & (and) (or) ~ (not) To specify a decision point in Matlab, the if statement is used as follows condition if x <= 0 flag = 1 statement required to indicate of structure Statement(s) evaluated if condition is TRUE 5
One Conditional If Statement if condition statement 1 statement 2 FALSE If (condition) Enter if structure TRUE Execution of Command Statements Exit if structure IF - ELSE Statement Enter if structure if condition statement 1 statement 2 else statement 1 statement 2 FALSE Execution of else Command Statements If (condition) TRUE Execution of Command Statements Exit if structure Multiple Conditions: IF ELSEIF - ELSE Statement if (condition 1) statements elseif (condition 2) statements elseif (condition 3) statements elseif (condition 4) statements else statements 6
Example Create a Matlab script (M-file) to acquire users age then specify what decade they were born Note indenting of statements in if structure Note new command: disp How does the output of disp differ from when ; is not used? age = input ('How old are you? '); if age <= 6 disp('wow, you are a 21st Century child!') elseif age > 6 & age <= 16 decade = '1990s'; else disp('you are too old to tell. Sorry.') disp('you were born in ') disp(decade) Loop Structures: While & For Loop structures can be used in a program to execute a block of statements multiple times The number of times the statements are executed can be specified (for loop), or can be unspecified and based on a condition (while loop) for x = [1 2 3 4 5] statement 1 statement 2 while x < 5 statement 1 statement 2 While Loops Enter loop FALSE While (condition) TRUE Exit loop Execution of Command Statements 7
Examples of Where a While Loop Could be Used To have program run again if requested To Count Example: Write a short program which counts by 2s (The concept of counting can be used in a number of ways to keep track of how many times a while loop has run, and to then make use of that count) To keep a running sum (similar to counting ) Example: Write a short program which allows user to sum a series of numbers Example Question Example Let s modify our previous file by adding a while loop to allow the user to run the program again again = 1; while again == 1 age = input ('How old are you? '); if age <= 4 disp('wow, you are a 21st Century child!') elseif age > 4 & age <= 14 decade = '1990s'; else disp('you are too old to tell. Sorry.') disp('you were born in ') disp(decade) again = input('type the number 1 to run again, 0 to stop: '); 8
Using Strings with IF & WHILE Conditions What is the problem with the following code? month = input('what is your birth month?','s'); if month == 'January' disp('your birthstone is Garnet') elseif month == 'February' disp('your birthstone is Amethyst') elseif month == 'March' abc == defghij is like comparing [1 2 3] == [1 2 3 4 5 6] Strings are arrays of characters. To use strings in logic comparisons, dimensions must agree Logical Comparison of Arrays in MATLAB Numbers 4 == 4 Ans = 1 (1 ~ True) 4 == 2 Ans = 0 (0 ~ False) 4 == [ 4 3 2] (OK) Ans = 1 0 0 4 is treated as scalar and compared to each component of array [4 3] == [4 3 2 1] ERROR: Matrix dimensions must agree Strings y == y Ans = 1 (1 ~ True) y == n Ans = 0 (0 ~ False) y == yes (OK) Ans = 1 0 0 y is treated as scalar characterand compared to each component of array no == yes ERROR: Array dimensions must agree How is this related to dummy proofing user input? doagain = 'y'; while doagain == 'y' doagain == 'Y' disp( While loop executing') doagain = input('would you like to run this program again? y/n: ','s '); while doagain ~='y' & doagain ~='Y' & doagain ~='n' & doagain ~='N disp('error: You must respond with a single character, y or n') doagain = input('would you like to run this program again? y/n: ','s'); This code works fine as long as user types in a single character. Problem occurs when user responds with yes. Program terminates without error ( yes ~= y gives [0 1 1] which is FALSE) leaving user wondering what happened. 9
Fix to problem in previous slide doagain = 'y'; while doagain(1) == 'y' doagain(1) == 'Y % Enter program commands here doagain=input('run again?','s'); while doagain(1) ~= 'y' & doagain(1)~= 'Y' & doagain(1)~= 'n' & doagain(1) ~= 'N' doagain=input('error: You must respond with a y or n:, s ) This would NOT work doagain = 'y'; while doagain == 'y' doagain == 'Y doagain == yes doagain == YES disp( While loop executing') doagain = input('would you like to run this program again? y/n: ','s '); This code works ok as long as user types in a single character or 3 character response (i.e. y n or yes ). Program Error occurs when user responds with no, which causes a 2 character array to be compared to a 3 character array in while condition. Commands Learned Input commands load Input uigetfile * : Output commands disp ; save * Programming structures if else elseif - while - * = See textbook and review on your own 10