You are on page 1of 25

3/24/2019

CSCI-1190
Beginning Programming for Engineers

 Today’s class
o Lecture 3
 Assignment
o Homework 3 on Grader
o zyBook 3 Activity on zyBooks
 Lab 3 on Thursday
o Available at the end of the lecture time

1
CSCI-1190 Dr. Liu

Lecture 3

1. User defined functions (customized functions)


2. Program flow control
3. Relational and logical operations
4. Save and load data to/from data files

CSCI BP Liu 2

1
3/24/2019

The Benefits of Using Functions

 Break complex problems into sub-problems


 Easier to design, to code, and to test a sub-problem
 Can be shared among programs
 Can be called(used) multiple times

CSCI BP Liu 3

User Defined Functions vs. Built-in Functions

 MATLAB built-in functions come with the MATLAB framework.


They are a part of the MATLAB language

Examples: sin(), cos(), plot(), max(), etc.

 User defined functions (customized functions) are written by


users(programmers) using the MATLAB language

Examples: myfunc1( ), myfunc2 ( ), etc

CSCI BP Liu 4

2
3/24/2019

The Syntax of MATLAB Function Definition


function [out1, out2, …, outN] = myfunc (in1, in2, …, inN)
1. The above function is the keyword you must use to define a function.
2. A function must have a name, such as myfunc used above.
3. A function normally has input parameters, such as (in1,in2,in3, ..., inN)
for the caller to pass information(arguments) to the function
4. A function normally has return variables, such as [out1, out2, …, outN]
for the caller to use
5. A function must be saved in an .m file to be shared, and the file must
have the same name as the function’s name. Example: myfunc.m file
https://www.mathworks.com/help/matlab/ref/function.html
CSCI BP Liu 6

https://www.mathworks.com/help/matlab/matlab_prog/create-functions-in-files.html

Function Example
function [c] = pythagf (a, b)
% The pythagf calculates hypotenuse
c = sqrt(a^2 + b^2);
end

o Save to pythagf.m file


o a and b are input parameters. (inputs of the functions)
o c is a return variable. (outputs of the functions)
o To use the function: y = pythagf (21, 30)

CSCI BP Liu 7

3
3/24/2019

Function’s Return Variables

function [outVar] = pythagf(a, b)


outVar = sqrt(a^2 + b^2);
end

 The return variable(s) must be defined inside the function

CSCI BP Liu 8

Multiple Return Variables


function [r1,r2] = quadratic (a,b,c)
% QUADRATIC finds roots.
d = b^2 – 4*a*c;
r1 = (-b - sqrt(d)) / (2*a);
r2 = (-b + sqrt(d)) / (2*a);
end
% Call the function to get the roots (return values)
[q1,q2] = quadratic(1,-5, 6)
 Return variables r1 and r2 are defined inside the function
 (1, -5, 6) are arguments passed to the function’s parameters (a, b, c)
in order
 q1 and q2 get values from r1 and r2
CSCI BP Liu 9

4
3/24/2019

How to Call (Use) a Function? function [c] = pythagf(a, b)


% The pythagf calculates hypotenuse
Examples:
c = sqrt(a^2 + b^2);
pythagf(3,4)
end
y = pythagf(3,4)
pythagf(20, 21) *10
y = pythagf(30, 40) + pythagf(8, 15)
f=5
pythagf ( f+1, 10 )

CSCI BP Liu 10

Good and Bad Function Definition and Call Examples

% Good Example pythagf.m: % Bad Example:


function [c] = pythagf(a, b) function pythagf(a, b)
c = sqrt(a^2 + b^2); c = sqrt(a^2 + b^2);
end end
>> pythagf(3,4) + 9 >> pythagf(3,4) + 9

% Error using pythagf


% Too many output arguments.

 A function must define return variable(s) for the caller to use the
result from the function.
CSCI BP Liu 11

5
3/24/2019

The Order of the Parameters, Arguments, and Return Variables


 zyBook Participation Activity 3.7.6
A function can return fewer variables than specified in the function
definition, in which case the last returned output(s) are ignored.
Example:
function [ surfaceArea, baseArea, vol ]= ConeVals (radius, height)
 [ surf, base, vol ] = ConeVals ( rds, hght ); %Call function
Wrong: [ base, surf, vol ] = ConeVals ( rds, hght ); %base is surf
 [ surfArea ] = ConeVals ( rds, hght );
Wrong: [ vol ] = ConeVals ( rds, hght ); % vol is surfaceArea
CSCI BP Liu 12

Summary on How to Call/Use Functions


 Call a function by its name without .m suffix
 A function to be called must be in the current folder, in a preset
search path, or be given its full path
 Do not click “Run” or “Run Section” buttons to test a function if a
function has input parameters defined
 Pass the arguments in the same order of the parameters defined in
the function
 Receive the return values in the same order of the return variables
defined in the function
CSCI BP Liu 14

6
3/24/2019

Variable Scopes: Base Workspace vs. Local Workspace

% scopescript.m function [r1,r2] = quadvec(a,b,c)


a0 = [ 1 2 3 4 ]; d = b.^2 - 4.*a.*c;
b0 = [ 6 7 8 9 ]; r1 = (-b - sqrt(d)) ./ (2*a);
c0 = [ 10 11 12 13 ]; r2 = (-b + sqrt(d)) ./ (2*a);
[q1,q2] = quadvec(a0, b0, c0) end

CSCI BP Liu 15

Variable Scope: Base Workspace vs. Local Workspace, Cont.


 Variables a0, b0, c0, q1, and q2 are available in the base workspace
 Variables a, b, c, d, r1, and r2 are local variables and available inside the
function in the local workspace. They only exist when the function is
running.
 The caller (the script file here) only has access to the variables in the base
workspace
 The function’s input parameters and output variables are the way to share
data between the caller and the function
 Exception is global type variables (need to define specifically).

CSCI BP Liu 16

7
3/24/2019

Example: Variable Scope (zp 3.7.5)

function out = PlusOne( inVar )


inVar = inVar + 1; What is the value of inVar in the
out = inVar; global workspace after executing:
end inVar = 1;
out1 = PlusOne(inVar);

CSCI BP Liu 17

Functions’ help message


 The “help” command displays how to use the function
>> help
>> hep funcName
 The help message is the first group of comments in a function file.
function [c] = pythagf(a, b)
% pythagf computes hypotenuse.
c = sqrt(a^2 + b^2);
end
>> help pythagf
% displays “pythagf computes hypotenuse.”
CSCI BP Liu 18

8
3/24/2019

Example: Write Help Message

CSCI BP Liu 19

Common Errors When Writing/Using Functions


 Name the function file differently than the defined function’s name
 The function file is not in the same folder with the script file which uses
the function, and is not the current folder or in the search path
 Forget to define return variables
 The return variables are not named the same as the variables defined
in the function.
 Modified functions without saving changes
 Click “Run” or “Run section” buttons to run the function which has
input parameters defined.
 Use variables not in the correct
CSCI BP Liu scope 20

9
3/24/2019

Scripts vs. Functions


o Write scripts as main programs
o A script normally starts with clear and clc commands
o A script file doesn’t have parameters and return variables
o A script file can call functions and provide the arguments to the
functions’ parameters and get the results from functions’ return
variables.
o You can click the “Run" or “Run Section” buttons to run a script

CSCI BP Liu 21

Functions vs. Scripts


 Use functions as subprograms and call them from main scripts
 A function must not use “clear” command in it. The “clear” will
deletes all arguments passed into the function.
 The function parameters and return variables are the way to
share data with the caller
 A function must be called either in the Command Window or
from another program
 Should not click the “Run" button to run a function (no arguments
to satisfy the parameters)
CSCI BP Liu 22

10
3/24/2019

Question

1. Do you normally want to have a “clear” command inside a


function?

2. Can you test/run a function by clicking the “Run” button on the


top of the Editor window if the function has input parameters?

CSCI BP Liu 23

Summary on Writing/Using Functions


o The benefits of using functions.
o How to write a function?
o How to call a function? (input parameters, output return
variables)
o How to test a function?
o Variable scopes: base workspace vs. local workspace
o How to include help text message in a function?
o How to display the help message of a function?
CSCI BP Liu 24

11
3/24/2019

Program Flow Control: Three Types of Program Flow

 Sequence Sequence Selection Repetition


(Loop)
 Selection
 Repetition

CSCI BP Liu 26

Conditional Selection Flowchart


The flowchart is a good tool
to design algorithms.

Only one of
them is
displayed.

CSCI BP Liu 27

12
3/24/2019

Flow Chart Symbols


 An oval indicates the
 The flowchart lists each beginning or ending of a
step necessary to perform section of code
a process  A parallelogram indicates an
 The flowchart is especially input or output
appropriate for designing  A diamond indicates a
complicated programs decision point
 A better way of  Calculations are placed in
communicating the logic of rectangles
a system

https://www.smartdraw.com/flowchart/flowchart-symbols.htm
CSCI BP Liu 28

Syntax on Conditional Flow Control


o If statement
if … end % check only one condition
if … else … end % check two conditions
if … elseif … elseif … else … end % check more conditions
o Switch statement
o Relational operators
o Logical operators
https://www.mathworks.com/help/matlab/ref/if.html
CSCI BP Liu 29

13
3/24/2019

“ if ” Statement
● Keyword if must pair with end
if condition 1
● A condition is a relational or logical expression
statement 1
resulting in a logical value: true or false
elseif condition 2
● Could have multiple conditions by using elseif
statement 2
● The nth condition is checked only when the
elseif condition n conditions before it (1 to n -1) are all false
statement 3
● If the nth condition is true, the conditions after it
... will not be evaluated
else ● The last else doesn’t have a conditional expression
statement 4 ● Only one or none statement is executed
end  (None statement is executed if all conditions result
CSCI BP in
Liu a false value and else is not used) 30

if Statement Example

score = input(‘input your score: ‘);


If score >= 60
grade = ‘pass';
else
grade = ‘fail';
end
disp(grade);

CSCI BP Liu 31

14
3/24/2019

if Statement Example
score =input('input your score number: ')
if score >=90
display('Excellent!')
elseif score >=80 & score <90 % do not need to evaluate score < 90
display('Very Good!')
elseif score >=70 & score <80 % do not need to evaluate score < 80
display('Not to bad')
elseif score >=60 & score <70 % do not need to evaluate score < 80
display(‘Passed')
else
display('Why?')
end CSCI BP Liu 32

Relational Operators
Relational Interpretation
Operators
a == b a equal to b ?
a ~= b a not equal to b ?
a<b a less than b ?
a <= b a less than or equal to b ?
a>b a greater than b ?
a >= b a greater than or equal to b ?
The two operands of a relational operator, such as, a and b above, must have
equal size matrices. 33
CSCI BP Liu 33

15
3/24/2019

Relational Condition Expressions


 The result of a relational expression is a logical value: true(1) or false(0)
• true (all low cases) is represented by 1 (all low cases)
• false (all low cases) is represented by 0
 The operands of relational operators must have equal size
An error example:

 Relations can be further combined using logical operators.


Example: a > 5 & a < 10
34
CSCI BP Liu 34

Example: find intersection point of two lines


y1 = m1*x + b1
y2 = m2*x + b2

if m1 ~= m2 % avoid dividing by zero


x = (b2 - b1) / (m1 - m2); y = m1*x + b1;
else
disp('Lines are parallel!')
end

CSCI BP Liu 35

16
3/24/2019

Logical Data Type

logical value 1, true

logical value 0, false

CSCI BP Liu 36

Examples: Logical Operations on Arrays. The Results are logical arrays

 Relational operators have higher priority than the assignment operator.


CSCI BP Liu 37

17
3/24/2019

Logical Operators
 Logical operators operate on logical data type
 Logical operations can combine multiple relational
expressions
Example: a > 5 & a < 10
 Logical operators
Operator Interpretation
& and
| or
~ not
CSCI BP Liu 38

Logical Operations Results


true & true true
Truth (1 & 1) (1)
Table of true & false false
Logical (1 & 0) (0)
Operations false & false false
true | true true
true | false true
false | false false
~false true
CSCI BP Liu
~true false 39

18
3/24/2019

Example of Logical Operations


% Create variables a and b:
a = true (logical 1)
b = false (logical 0)
% Assume the above a and b logical values, we have
the following table
Logical Operation Result Interpretation
a&b false (0) a and b
a|b true (1) a or b

~a false (0) not a


CSCI BP Liu 40

Examples of Combining Relational Expressions Using Logical Operators

% calculate speed when both time % A different implementation


% and dist are not zero
time = input(‘Please input time: ‘)
dist = input(‘Please input dist: ‘) if (time ~= 0) & (dist ~= 0)
if (time == 0) | (dist == 0) speed = dist / time;
speed = 0; else
else speed = 0;
speed = dist / time; end
end
CSCI BP Liu 41

19
3/24/2019

A Note on MATLAB’s true or false Value

In MATLAB, false is 0 or empty, and everything else is true.


Examples:
>> 2 & 3 % ans = logical 1

>> 0 & 3 % ans = logical 0

>> 2 | 3 % ans = logical 1

CSCI BP Liu 42

Precedence Rules for Logical Operators

CSCI BP Liu 43

20
3/24/2019

Note: Difference Between Mathematic Formulas and Code Implementation

Example 1:
 A mathematic expression: 16 < usrAge < 25
 MATLAB code implementation of the above formula
o Must uses logical operators to combine relational operations
(usrAge > 16) & (usrAge < 25)
Example 2:
 Mathematic expressions:
a x b, or ab
 MATLAB code:
a*b
CSCI BP Liu 44

Code Example for a Conditional Process Flowchart


%% Script to play a basic hi-lo number game.
M = 100; myNum = floor(1+M*rand()); %Computer number
yourNum =input('Enter your guess: ');
if yourNum < myNum % Display message
disp('Too small!');
elseif yourNum > myNum
disp('Too big!');
else
disp('That is it!');
End

fprintf( 'My number is %f ; You number is %f\n', myNum, yourNum);


CSCI BP Liu 45

21
3/24/2019

Switch – Execute One of Several Groups of Statements


 Syntax
switch switch_expression
case case_expression
statements
case case_expression
statements
...
otherwise
statements
end

https://www.mathworks.com/help/matlab/ref/switch.html
CSCI BP Liu 46

Example: switch has Cases of numeric Datatype

month = input('input a month using a number 1 to 5: '); % month is a numeric value


switch(month) % month is a variable
case (1)
fprintf('January\n' );
case 2
fprintf('February\n' );
case 3
fprintf('March\n' );
case 4
fprintf('April\n' );
case 5
fprintf('May\n' );
otherwise
fprintf('invalid input\n' );
end CSCI BP Liu 47

22
3/24/2019

Example: switch has Cases of string Datatype


grade = input('What is your letter grade? ', 's'); %grade is a string datatype
switch (grade) % grade is a variable
case 'A' % remember to use the single quotation mark for a string
fprintf('Excellent!\n' );
case 'B'
fprintf(Good!' );
case 'C'
fprintf(‘Not bad!\n' );
case 'D'
fprintf(‘Passed\n' );
case 'F'
fprintf(‘Work harder!\n' );
otherwise
fprintf('Invalid grade\n' );
end CSCI BP Liu 48

Coding Style: Use Indent to Keep Code Readable


 Indent code within blocks
 Indent one level for EACH nested block of code
 Indenting makes easier to write and read your code, and debug
 Example

CSCI BP Liu 49

23
3/24/2019

Save Variables (Data) to a File

save 'filename'
Saves all variables in the workspace to filename.mat
save 'filename' x y z
Saves the variable x, y, and z to filename.mat
whos
Lists all the variables in the current workspace.
whos -file 'filename'
Lists all the variables save in filename.mat
CSCI BP Liu 50

Load Variables from a File to Workspace

load 'filename'
Load all the variables stored in filename.mat into the
workspace. (Existing Workspace variables not stored in
filename.mat are unchanged.)

load 'filename' x y z
Load the variables x, y, and z from filename.mat into the
workspace.

CSCI BP Liu 51

24
3/24/2019

An m-file’s name must be a valid variable name

 Your computer probably adds (#) to a file’s name when


downloading a file to where the same file already exists.

Examples:
inclass(1).m or inclass(2).m, …, filename(n).m

 The above file names are Invalid in MATLAB. You must remove
the (#) portion by renaming it, or some other ways.

CSCI BP Liu 52

“ctrl_c”, “pwd” and “ls” commands


o Type “pwd” (without the quotation marks) in the
Command Window displays the current folder path
o Type “ls” displays the files of the current folder in the
command Window
o The above two commands are useful to check if a
function or a file is contained in the current folder.
o Press both ctrl and c keys to stop a running process. You need
first click the mouse in the Command Window to make sure it is
ready to take input..
CSCI BP Liu 53

25

You might also like