Uploaded by BlockchainExpo İstanbul

BIL113E LN03 Functions

advertisement
BIL113E Lecture Notes #3
2020-21 Spring
Overview of MATLAB Program Files
BIL113E INTRODUCTION TO
SCIENTIFIC & ENGINEERING
COMPUTING
 If you want to save your workspace, i.e., your variables,
 When you have a repeated sequence or commands,
 If you want to save your commands for future references, you might
want to store your commands in files.
Lecture Notes #3
Functions
 There are three types of basic MATLAB® files:
Workspace (extension *.mat)
2021-2022 Spring Term
Script (extension *.m)
Gokhan Cevikbilen, Ph.D.
Department of Civil Engineering
Geotechnical Lab #140413
cevikbil@itu.edu.tr
Function (extension *.m)
MAT-file
M-file
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
Workspace Files
Workspace Files
 The workspace contains variables that you create or import into
MATLAB® from data files or other programs. You can view and edit
the contents of the workspace in the Workspace browser or in the
Command Window.
 You can create a workspace file in the following ways:
Click the Save Workspace button on the Home tab.
Use the save function. For example, save filename
creates/overwrites the file filename.mat and saves all the
variables to this file. If a filename is not specified, MATLAB® saves
the workspace to matlab.mat file.
 Workspace variables do not persist after you exit MATLAB®. To use
your data across multiple sessions, save it to a compressed file with
a ”.mat” extension called a MAT-file. You can restore saved data by
loading a MAT-file back into MATLAB®.
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
2
 To load the variables from a workspace file, simply use:
load filename
3
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
4
1
BIL113E Lecture Notes #3
2020-21 Spring
Scripts
Scripts
 A script M-file is literally a list of sequential MATLAB® commands that
can be saved and used for future references.
 You can create a new script in the following ways:
Highlight commands from the Command History, right-click, and
select Create Script.
 Once it is saved, running the script file will basically execute all
commands within.
Click the New Script button on the Home tab.
Use the edit function. For example, edit new_file_name
creates (if the file does not exist) and opens the file
new_file_name. If filename is not specified, MATLAB® opens a
new file called Untitled.
 If needed, corrections or changes can be made to the commands in
the file.
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
5
Scripts
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
6
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
8
Scripts
 Similarly, you can run the script by typing the script name on the
command line and press Enter. For example, to run the
new_file_name script, type new_file_name or;
 Click the Run button on the Editor tab.
 Let’s create a script with name eq_system that provides the solution
matrix for the given equation system:
𝑥 + 2𝑦 + 3𝑧 = 1
3𝑥 + 3𝑦 + 4𝑧 = 1
2𝑥 + 3𝑦 + 3𝑧 = 2
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
7
2
BIL113E Lecture Notes #3
2020-21 Spring
Input and Output Commands
Functions
Command
Description
disp(a)
Displays the contents of the variable a.
disp('text')
Displays the text in quotes, i.e. text
format
Controls the output display format (refer to Lecture Notes #2)
 A function is a group of statements that together perform a task. In
MATLAB®, functions are defined in separate files (M-files). The name
of the file and of the function should be same.
x = input('text')
Displays the text in quotes, waits for user input from the keyboard and stores
the value in x.
x = input('text', 's')
Same as above, except stores the value as a string.
y = menu('title',
'option1', 'option2',
...)
Displays a menu with title and choices (buttons) of option1, option2, ...
Stores the user selection index in the variable y as 1, 2, ...
 Functions operate on variables within their own workspace, which is
also called the local workspace, separate from the workspace you
access at the MATLAB® command prompt which is called the base
workspace.
 Functions can accept more than one input arguments and may return
more than one output arguments.
For more info: https://www.mathworks.com/help/matlab/functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
9
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
10
Types of Functions
Anonymous Functions
 Built-in functions
 An anonymous function is like an inline function in traditional
programming languages, defined within a single MATLAB® statement.
These are MATLAB®'s built-in functions such as sin, plot, etc.
 It consists of a single MATLAB® expression and any number of input
and output arguments.
 User-defined functions
Anonymous functions
 You can define an anonymous function right at the MATLAB®
command line or within a function or script.
Local functions
Primary functions and sub-functions
 This way you can create simple functions without having to create a
file for them.
Nested functions
Private functions
For more info: https://www.mathworks.com/help/matlab/functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
11
For more info: https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
12
3
BIL113E Lecture Notes #3
2020-21 Spring
Primary and Sub-Functions
Nested Functions
 Any function other than an anonymous function must be defined
within a file. Each function file contains a required primary function
that appears first and any number of optional sub-functions that
comes after the primary function and used by it.
 You can define functions within the body of another function. These
are called nested functions. A nested function contains any or all of
the components of any other function.
 Nested functions are defined within the scope of another function and
they share access to the containing function's workspace.
 Primary functions can be called from outside of the file that defines
them, either from command line or from other functions, but subfunctions cannot be called from command line or other functions,
outside the function file.
 Sub-functions are visible only to the primary function and other subfunctions within the function file that defines them.
For more info: https://www.mathworks.com/help/matlab/matlab_prog/local-functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
13
For more info: https://www.mathworks.com/help/matlab/matlab_prog/nested-functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
14
Private Functions
Functions (Summary)
 A private function is a primary function that is visible only to a limited
group of other functions. If you do not want to expose the
implementation of a function(s), you can create them as private
functions.
 Functions are programs (or routines) that accept input arguments and
return output arguments.
 Each M-file function (or function or M-file for short) has its own area of
workspace, separated from the MATLAB® base workspace.
 Private functions reside in subfolders with the special name private.
 They are visible only to functions in the parent folder.
 Often, you store a function in its own file. In
that case, the best practice is to use the
same name for the function and the file,
since MATLAB® associates the program
with the file name.
For more info: https://www.mathworks.com/help/matlab/matlab_prog/private-functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
15
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
16
4
BIL113E Lecture Notes #3
2020-21 Spring
Creating Functions
Creating Functions
Syntax for Function Definition
Example
 The default pop-up function window in MATLAB®
function keyword (required)
Use lowercase characters
--
output arguments (optional)
one output → specify the output
name after the function keyword.
function area
multiple outputs → specify the
output names in square brackets
function [perimeter,area,volume]
no output → nothing or empty
square brackets
function
function []
Function name (required)
use the same name for both the
function file and the first function
within the file
function area=area_calculator
(filename will be area_calculator.m)
Input arguments (optional)
If your function accepts any
inputs, enclose their names in
parentheses after the function
name. Separate inputs with
commas.
function area=area_calculator(b,h)
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
17
Creating Functions
18
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
Example: Anonymous Function
 Anonymous function syntax:
 f = @(arglist) expression
 Examples:
>> sq = @(x) x*x
sq =
function_handle with value:
@(x)x*x
>> sq(5)
ans =
25
>> pow = @(x, n) x.^n;
>> pow(3,2)
ans =
9
For more info: https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
19
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
20
5
BIL113E Lecture Notes #3
2020-21 Spring
Example: Primary and Sub-Function
Example: Nested Function
 File name: quadratic.m
 File name: quadratic2.m
function [x1,x2] = quadratic(a,b,c)
%quadratic Quadratic equation solver.
%
quadratic(a,b,c) returns the roots
%
of a quadratic equation.
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end
function [x1,x2] = quadratic2(a,b,c)
Primary function
function dis = disc(a,b,c)
%dis Calculates the discriminant.
dis = sqrt(b^2 - 4*a*c);
end
Sub-function
disc;
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
% begin nested function disc
function disc
d = sqrt(b^2 - 4*a*c);
end
% end nested function disc
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
Nested
function
Primary function
end
21
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
22
Example: Private Function
Scripts vs Functions
 File name: quadratic3.m
 Scripts are the simplest type of program, since they store commands
exactly as you would type them at the command line.
function [x1,x2] = quadratic3(a,b,c)
%quadratic Quadratic equation solver.
%
quadratic(a,b,c) returns the roots
%
of a quadratic equation.
d = disc(a,b,c);
x1 = (-b + d) / (2*a);
x2 = (-b - d) / (2*a);
end
 Functions provide more flexibility, primarily because you can pass input
values and return output values.
Primary function
 Variables created in a script are stored in MATLAB® base workspace,
whereas each function file has its own workspace.
 File name: private/disc.m
function dis = disc(a,b,c)
%dis Calculates the discriminant.
dis = sqrt(b^2 - 4*a*c);
end
Private function
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
23
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
24
6
BIL113E Lecture Notes #3
2020-21 Spring
Scripts vs Functions
Scripts vs Functions
 Let’s compare a script and a function that computes area of a triangle:
 Let’s compare a script and a function that computes area of a triangle:
Script Version 1:
Script Version 1:
b = 5;
h = 3;
a = 0.5*(b*h)
b = 5;
h = 3;
a = 0.5*(b*h)
Script Version 2:
Script Version 2:
b=input('please enter the base length ');
l=input('please enter the height ');
a=b*l/2
Function Version:
b=input('Please enter the base length ');
l=input('Please enter the height ');
a=b*l/2
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
>> triarea(6,3)
function [a] = triarea(b,h)
a = b*h/2;
end
25
ans =
9
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
26
Adding Functions to Scripts
Exercises
 MATLAB® scripts, including live scripts, can contain code to define
functions.
 Let’s write a code to calculate the total price to be paid for building and
painting a wooden cone.
 You can either add local functions to your script which won’t be visible
to other functions and can not be called using command window or;
 You can call a global function in a script file.
Total cost = (Material unit price) * (Volume of the cone)
+ (Paint unit price) * (Area of the cone)
 Input data:
 mat_price=1000
 paint_price=100
 r=0.3 m
 h=0.6 m
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
27
BIL113E Lecture Notes #3 – Gokhan Cevikbilen, Ph.D.
28
7
Download