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

Slides:



Advertisements
Similar presentations
A number of MATLAB statements that allow us to control the order in which statements are executed in a program. There are two broad categories of control.
Advertisements

5.04 Apply Decision Making Structures
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Decision-Making Programs
Introduction to C Programming
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Chapter 5 Decisions. Outline and Objectives Relational and Logical Operators If Blocks Select Case Blocks.
Conditional Statements Introduction to Computing Science and Programming I.
Lecture 8 Logical Operations Logical functions & Relational operators © 2007 Daniel Valentine. All rights reserved. Published by Elsevier.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Branches and Loops Selim Aksoy Bilkent University Department of Computer Engineering
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
General Computer Science for Engineers CISC 106 Lecture 08 Dr. John Cavazos Computer and Information Sciences 2/27/2009.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Week 7 - Programming I Relational Operators A > B Logical Operators A | B For Loops for n = 1:10 –commands end.
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Chapter 4 Making Decisions
Chapter 8 Branching Statements and Program Design.
Introduction to C Programming
Programming with MATLAB. Relational Operators The arithmetic operators has precedence over relational operators.
MATLAB and SimulinkLecture 11 To days Outline  Introduction  MATLAB Desktop  Basic Features  Branching Statements  Loops  Script file / Commando.
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Selection Programming EE 100. Outline introduction Relational and Logical Operators Flow Control Loops Update Processes.
CSE123 Lecture 3 Different types of Variables Logical operators, Conditional Statements and If Blocks.
MATLAB FUNDAMENTALS: CONTROL STRUCTURES – LOOPS HP 100 – MATLAB Wednesday, 10/1/2014
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
CMPS 1371 Introduction to Computing for Engineers CONDITIONAL STATEMENTS.
1 Computer Programming (ECGD2102 ) Using MATLAB Instructor: Eng. Eman Al.Swaity Lecture (4): Control Flow (Chapter 2)
CS 170 – INTRO TO SCIENTIFIC AND ENGINEERING PROGRAMMING.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Conditional Expression One of the most useful tools for processing information in an event procedure is a conditional expression. A conditional expression.
Introduction to Matlab Module #4 Page 1 Introduction to Matlab Module #4 – Programming Topics 1.Programming Basics (fprintf, standard input) 2.Relational.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
CSE123 Lecture 3 Files and File ManagementScripts.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Review if imag(x) > 0 fprintf('Sorry, but I don''t understand complex numbers.\n'); return end if x < 10 % leave this out, type the next line first, and.
Chapter Making Decisions 4. Relational Operators 4.1.
Chapter 3 Control Structures. The If…Then Statement The If…Then statement is a Decision statement = that executes a set of statements when a condition.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
1 CS1371 Introduction to Computing for Engineers Control Statements 9/4/2003.
Fall 2006AE6382 Design Computing1 Control Statements in Matlab Topics IF statement and Logical Operators Switch-Case Disp() vs fprintf() Input() Statement.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
31/01/ Selection If selection construct.
Conditional Logic in MATLAB By Bruce Raine. How to do a basic IF – END structure in MATLAB if MATLAB Commands end i.e. do the MATLAB commands if the conditional.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Today… Operators, Cont. Operator Precedence Conditional Statement Syntax. Winter 2016CISC101 - Prof. McLeod1.
The Ohio State University
Matlab Programming for Engineers
Introduction to Programming for Mechanical Engineers (ME 319)
Control Statements in Matlab
Chapter 4: Making Decisions.
Chapter 4: Making Decisions.
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB: Structures and File I/O
Introduction to MATLAB
Lecture 3 MATLAB programming (1)
More Selections BIS1523 – Lecture 9.
Selection Statements.
Chapter 5 Decisions.
Selection Statements Chapter 3.
Presentation transcript:

MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES HP 101 – MATLAB Wednesday, 9/24/2014

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 

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:

Enough Review – On to new stuff!

Display Output – Part I  Remember the disp command?  x=15;  disp(x); 15  x = (1:5);  disp(x);  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:  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 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 = [ ] 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 = [ ]; Index = find(A > 3); >>Index = 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