matlab fundamentals: input/output logic control structures

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

Upload: aizza

Post on 06-Jan-2016

74 views

Category:

Documents


1 download

DESCRIPTION

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." - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

MATLAB FUNDAMENTALS:INPUT/OUTPUTLOGICCONTROL STRUCTURES

HP 101 – MATLABWednesday, 9/24/2014

www.clarkson.edu/class/honorsmatlab

Page 2: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 3: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 4: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 5: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 6: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 7: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Enough Review – On to new stuff!

Page 8: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 9: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 10: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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!!

Page 11: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 12: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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 directorycd 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’);

Page 13: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Whew…

Ready for some real fun?

Page 14: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

The Logical Data Type (8.1)

The Logical Data Type Two values: True or False

If you Try to use them as numbers:True == 1 False == 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

Page 15: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Relational Operators (3.3)

Relational operators Two numerical or string operands Yield a logical result (true or false)

Syntax : a1 op a2

a1 & a2 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

Page 16: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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 ==bans =

0

Page 17: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Relational Operators (cont.)

A few examples4 < 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!

Page 18: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Logical Operators (cont.)

Logical Operators: Operators with one or two logical operands that

yield a logical result syntax: Exp1 op Exp2

Exp1 & Exp2 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

Page 19: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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 > 10But what if b = 0? a/b will return Inf instead of a numberTo 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.

Page 20: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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);

Page 21: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Logical Operators (cont.)

Hierarchy of Operations1. All Arithmetic operators are evaluated2. All relational operators (==, ~=, >, >=, <, <=)3. All ~ operators4. All & and && operators from left to right5. 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 otherwiseisempty(a) Returns true if a is an empty array and false otherwiseisinf(a) Returns true if a is NaN (not a number) and false otherwiseisnumberic(a) Returns true if a is a numeric array and false otherwiselogical(a) Coverts numerical values to logical valuesfind(array op cond) Section 8.3.1

Page 22: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 23: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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

Page 24: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

Branches (cont.)

The if ConstructForm:if control_expr_1

Statement 1Statement 2…

elseif control_expr_2Statement 1Statement 2…

elseStatement 1Statement 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

Page 25: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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.

Page 26: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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 < 0 || 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?????

Page 27: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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.

Page 28: MATLAB FUNDAMENTALS: INPUT/OUTPUT LOGIC CONTROL STRUCTURES

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