# MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014 www.clarkson.edu/class/honorsmatlab.

## Presentation on theme: "MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014 www.clarkson.edu/class/honorsmatlab."— Presentation transcript:

MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014 www.clarkson.edu/class/honorsmatlab

Quote/Video of the week  "I always love that the third derivative is called jerk. We always call the fourth one the guy who didn't call us back." Prof. Fowler Calculus II  https://www.youtube.com/watch?v=rz5TGN7eUcM https://www.youtube.com/watch?v=rz5TGN7eUcM

Basic Input - Review  Numerical Input  x = input ('What is your favorite number');  a = input ('Enter array A in square brackets');  Allows user to enter numerical data  Only numbers are accepted, though

Strings in MATLAB  A string is a fancy word for anything not numeric  In MATLAB ' single quotation marks ' denotes a string.  Ex:  Bob  Area  physics5

Strings in MATLAB – Input  To input strings in MATLAB, it is easy  color = input('Your favorite color?','s');  name = input(‘Which TA do you like more?','s');  x = input('What is your favorite number?','s');  The only real difference is the trailing 's'  Numbers can be represented as strings, too

Strings in MATLAB – Conversions  To change a number into a string:  xS = num2str(x);% xS is now a string!  To piece numbers and strings together:  y=['The values in the array are: ' num2str(x)];  Yields just a single line of output: disp(y) The values in the array are: 1 2 3 4 5

Enough Review – On to new stuff!

Display Output – Part I  Remember the disp command?  x=15;  disp(x); 15  x = (1:5);  disp(x); 1 2 3 4 5  Advantages:  Cleaner – does not print variable name  You can organize the output more than being at the mercy of MATLAB

Display Output – Part II  For two separate lines:  disp(‘The values of the array are: ’);  disp(x);  Output: The values of x are: 1 2 3 4 5  More professional and easier to read

Graphical Input  [a,b] = ginput  Allows you to click on an image and get data points  Useful in real world problems  Powerful with image data  Look in HELP for more details!!

Additional I/O Methods:  Load From Files:  load  uiimport  importdata  From Excel:  xlsread, xlswrite  Output to Files:  fprintf(see HELP)  save(see Text)  Pages 237-238 and HELP for more details

Importing  When importing data:  The active directory must be the same as location of the input file.  3 Options Use cd command to change the directory cd C:\newdirectory\folder\folder Put the input file in the same folder as your code Include the name of the directory in the inport function importdata(‘C:\newdirectory\folder\folder\file’);

Whew…  Ready for some real fun?

The Logical Data Type (8.1)  The Logical Data Type  Two values: True or False If you Try to use them as numbers: True == 1False == 0  So what is the big deal? A logical value takes up only 1 byte of memory They will be very useful when trying to control how your program works

Relational Operators (3.3)  Relational operators  Two numerical or string operands  Yield a logical result (true or false) Syntax : a 1 op a 2 a 1 & a 2  the numerical or strings you wish to compare op  the logical operator  Relational Operators: ==Equal to ~=Not equal to >Greater than >=Greater than or equal to <Less than <=Less than or equal to

Relational Operators (cont.)  Be Careful! ==  equivalence operator =  assignment operator  Note:  Computers like to use numbers not theory Roundoff error >>a = 0; >> b = sin(pi); >> a ==b ans = 0

Relational Operators (cont.)  A few examples 4 < 7  true (1) 4 <= 7  true (1) 4 == 7  false (0) 4 > 7  false (0) 4 <= 4  true (1)  What about Arrays? a = [ 1 5 and b = [ 2 4 2 -3] 3 -7] a > b  [false true false false]  If the arrays are different sizes MATLAB will yield an error!

Logical Operators (cont.)  Logical Operators:  Operators with one or two logical operands that yield a logical result syntax:Exp 1 op Exp 2 Exp 1 & Exp 2  expressions or variables op  logical operator  Relational Operators: &  Logical AND &&  Logical AND with shortcut evaluation |  Logical Inclusive OR ||  Logical Inclusive OR with shortcut evaluation xor  Logical Exclusive OR ~  Logical NOT

Logical Operators (cont.)  Logical Operators (cont.)  Logical ANDs True if and only if both operands are true The difference between & and && & will evaluate both operands before returning a value && will return a value (of false) if the first operand is false Note: && will only work with scalar values When to use && Ex: We want to test the ratio of two variables and compare it to 10 x = a / b > 10 But what if b = 0?  a/b will return Inf instead of a number To avoid this: x = (b ~= 0) && (a / b > 10) If b equals zero then the first statement is false and it will return a value of false and will not evaluate the second statement.

Logical Operators (cont.)  Logical Operators (cont.)  Logical ORs  | and || The result of an inclusive OR operator is true if either input operand are true. Again we have | and || || will return a value of true if the first operand is true When to use which? It doesn’t really matter Note: Using || when appropriate will speed up the program  Logical Exclusive OR  xor The result of an exclusive OR operator is true: if and only if one operand is true and the other one is false NOTE: This operator is evaluated like a function! Syntax: >> a = 10; b = 0; x = xor(a,b);

Logical Operators (cont.)  Hierarchy of Operations 1. All Arithmetic operators are evaluated 2. All relational operators (==, ~=, >, >=, <, <=) 3. All ~ operators 4. All & and && operators from left to right 5. All |,||, and xor operators from left to right  Logical Functions  MATLAB has certain functions that return logical values Examples: ischar(a)  Returns true if a is a character array; false if otherwise isempty(a)  Returns true if a is an empty array and false otherwise isinf(a)  Returns true if a is NaN (not a number) and false otherwise isnumberic(a)  Returns true if a is a numeric array and false otherwise logical(a)  Coverts numerical values to logical values find(array op cond)  Section 8.3.1

Find Command A = [9 3 5 6 2 3 1]; Index = find(A > 3); >>Index = 1 3 4 Other variations: I = find(X,k) % returns first k indices I = find(X,k,’last’); % returns last k indices

Branches  Branches are MATLAB expressions that permits us to select specific sections of code (blocks) while skipping other blocks.  They are controlled by logical expressions.  They are: if switch try/catch

Branches (cont.)  The if Construct Form: if control_expr_1 Statement 1 Statement 2 … elseif control_expr_2 Statement 1 Statement 2 … else Statement 1 Statement 2 … end  If control_expr_1 is true  Then the program will execute Block 1 and then skip to the first executable line of code after the end statement.  If control_expr_1 is false  then the program will go to the next clause  If control_expr_2 is true  it will execute Block 2  If control_expr_2 is false  then the program will go to the next clause  The else clause will execute Block 3 (there is no logical expression associated with the else clause)  Please Note:  There can be only 1 “ if ” statement  There can be multiple “ elseif ” clauses  There can be only 1 “ else ” clause } Block 1 } Block 2 } Block 3

Branches (cont.)  The “if” construct  It is possible to nest “if” statements. The second level must be located within the “Statements” of the initial “if” statement or the “elseif” clauses. You must be careful to properly place the corresponding “end” of each “if” statement.  Good Programming Practice: For branches in which there are many mutually exclusive options, use a single “ if ” construct with multiple “ elseif ” clauses in preference over nestled if constructs.

The ‘if’ Example x = input('Guess my number '); if x == 17 disp('I think you entered my favorite number.'); elseif x > 16 && x < 18 disp('I want to say you got it, but you did not.'); elseif x 100 disp('You are not even close'); else disp('You are so far off it makes Joe cry'); end CAN YOU FIND THE ERROR IN THIS CODE?????

Branches (cont.)  The “ try/catch ” Construct  Special type of branching useful for dealing with problematic blocks of code  When used properly it will change how MATLAB deals with errors. Form: try Statement 1 Statement 2 … catch Statement 1 Statement 2 … end } Try Block } Catch Block When the “try/catch” construct is reached MATLAB will execute the statements in the Try Block If there are no errors then it will skip to the next line after the “end” If there is an error in the Try Block will execute the Catch Block, and then proceed. It will not end the program like it would normally when an error is reached.

Homework  8.2, 8.12  Before you leave:  Create a try/catch block that will prevent an error from an incorrect input from a user  Examples:  If an input is supposed to be a number, but the user enters a string  If an input is outside a prescribed range of numbers

Download ppt "MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014 www.clarkson.edu/class/honorsmatlab."

Similar presentations