Vous êtes sur la page 1sur 13

15.

1 Course Example - Electricity Consumption in Different Sectors: (1/2) Electricity Consumption in


Different Sectors
Increasing Automation with Functions
Course Example: Electricity Consumption
in Different Sectors

In a script, you're usually implementing a


complete data analysis workflow. 

For example, an analysis of electricity usage


data could contain these steps: 

 Import data from a file


 Preprocess the data
 Fit a polynomial to selected data
 Use the fit to predict usage at a future
date
 Plot the data and fitted model

The first few lines of your script define some


important parameters for the analysis:
 What's the name of the data file?
 What's the degree of the polynomial to
fit?
 What's the future date to predict usage
for?
What if you want to perform the analysis for a
different file? Or a different degree polynomial,
or a different future prediction date? You'll
need to manually modify their values in the
script and re-run it. 

A better solution is to create a function that


takes the filename, the degree of the
polynomial, and the future date as inputs. 

In this chapter, you'll learn to create and


call functions. You'll also learn how to
manage variables within functions and
understand how MATLAB finds a variable
or function.

15.2 Creating and Calling Functions: (1/6) Creating and Calling Functions
Creating and Calling Functions

Suppose you need to extract the three


largest elements from the vectors x and y.
You can write a script (as shown to the
right) that sorts the vectors and then
extracts the first three elements of the
sorted vectors.
Here, you are repeating the code to sort the vector and extract the three largest elements for the vectors x
and y. You can instead create a function that takes a vector as an input and outputs another vector
containing the top three elements.

Step 1 - Define a function at the bottom of the


script file.

The syntax for defining a function is similar to the


syntax for calling any MATLAB function with the
keyword function at the beginning. 

In this case, because only one output is needed, you do not need
  to enclose the output in square brackets.

Step 2 - Write the function body.


You can write one or more commands to
calculate the output using the inputs. These
commands form the function's body.
The input v is used in the function's body, on
line 5, and the output top3, calculated on
line 6, is returned as the function's output.

Step 3 - The function ends with the end


keyword.
After creating the function, you can call it with
specific inputs and outputs from within the script.
Here, the function call returns the three largest
elements of x. 

The syntax for calling a custom function is the


same as the syntax for calling any MATLAB
function. 

You can call the function again to find the


three largest elements of y.

Note that, because the function definition has


to be at the bottom of the script file, the
function calls should be above the definition.
Note that the input and output variables
names in the function call (y and top3y) don't
need to be same as the variables names used
in the function definition (v and top3).

Chú ý dấu () hoặc dấu [] nha

(Select all that apply) Which of the following


are valid ways to call a function called
myFunction which takes three inputs and
returns two outputs?
15.2 Creating and Calling Functions: (4/6) Create and Call a Function
TASK The script shown contains a function that takes a vector as an
input and returns another vector containing the three largest
1. Modify the script so that the function elements from the input vector.
takes two inputs. The second input
should represent the number of the function t = getLargestN(v)
largest elements to return. For example,  sortedV = sort(v,'descend');
t = getLargestN(v,5) t = sortedV(1:3);
should output a vector containing the five end
largest elements of v. Sau khi được điều chỉnh đây chính là đáp án
2. Modify the function call in the script and top5 = getLargestN(x,5)
store the five largest elements in a vector function t = getLargestN(v,N)
named top5. sortedV = sort(v,'descend');
t = sortedV(1:N);
end
TASK %This code is used to test the functions in this script.
Add another function call that calculates the 7
x = rand(1,10);
largest elements of x and store the result in a
vector named top7.
%Modify the function call
top5 = getLargestN(x,5)
top7 = getLargestN(x,7)

% Modify the function definition


function t = getLargestN(v,N)
sortedV = sort(v,'descend');
t = sortedV(1:N);
end
TASK %This code is used to test the functions in this script.
Now, modify the script and create another
x = rand(1,10);
function named getSmallestN that returns the
smallest set of elements. For example, 
%Modify the function call
b = getSmallestN(v,5) top5 = getLargestN(x,5)
should output a vector containing the five
top7 = getLargestN(x,7)
smallest elements of v. bottom5 = getSmallestN(x,5)

Call the two functions from the script and store %Modify the function definition
the five largest elements in a vector
named top5 and the five smallest elements in a function t = getLargestN(v,N)
vector named bottom5. sortedV = sort(v,'descend');
t = sortedV(1:N);
end

function b = getSmallestN(v,N)
sortedV = sort(v,'descend');
b = sortedV(end-N+1:end);
end
15.2 Creating and Calling Functions: (5/6) Electricity Usage Analysis Function
The script shown contains a function that takes function predictedusage = polyPrediction(filename)
the name of the data file as an input, fits a
predictdate = datetime(2020,1,1);
polynomial of degree 3, and returns the predicted
electricity usage on Jan 1, 2020. degree = 3;

The function also plots the actual and fitted usage % Import data
values.
TASK data = readtable(filename);
dates = data{:,1};
1. Modify the function definition so that the
usage = data{:,2};
function takes three inputs – the filename, sector = data.Properties.VariableNames{2};
the date on which the prediction is made,
and the degree of the polynomial. % Fill in the missing values.
usage = fillmissing(usage,'spline');
2. Also modify the body of the function such
that predictdate and degree are not % Fit polynomial and predict usage for a future date.
hardcoded. elapsedYears = years(dates-dates(1));
3. Now, modify the function call to predict c = polyfit(elapsedYears,usage,degree);
the usage on July 01, 2019 by fitting a
endDuration = years(predictdate-dates(1));
polynomial of degree 2.
usageFit = polyval(c,elapsedYears);
predictedusage = polyval(c,endDuration);

% Plot the predicted usage.


plot(dates,usage,'o-')
hold on
plot(dates,usageFit,'LineWidth',2);
plot(predictdate,predictedusage,'*r');
hold off
xlabel('Date')
ylabel('Usage')
title([sector ' usage'])
end
This code defines the file name for the electricity usage data.
filename_res = 'elec_res.csv';

Task 1 and Task 2


Modify the function call
predictdate1 = datetime(2019,07,01);
res_predictedusage =
polyPrediction(filename_res,predictdate1,2);

Task 1
Modify the function definition
function predictedusage =
polyPrediction(filename,predictdate,degree)
% Import data
data = readtable(filename);
dates = data{:,1};
usage = data{:,2};
sector = data.Properties.VariableNames{2};

% Fill in the missing values.


usage = fillmissing(usage,'spline');

% Fit polynomial and predict usage for a future date.


elapsedYears = years(dates-dates(1));
c = polyfit(elapsedYears,usage,degree);

endDuration = years(predictdate-dates(1));
usageFit = polyval(c,elapsedYears);
predictedusage = polyval(c,endDuration);

% Plot the predicted usage.


plot(dates,usage,'o-')
hold on
plot(dates,usageFit,'LineWidth',2);
plot(predictdate,predictedusage,'*r');
hold off
xlabel('Date')
ylabel('Usage')
title([sector ' usage'])
end
The electricity usage data for the industrial sector Electricity Usage Analysis
is stored in the file named elec_ind.csv.
Instructions are in the task pane to the left. Complete and
TASK
In the script, add another function call to predict submit each task one at a time.
the industrial usage on Jan 01, 2020 by fitting a
polynomial of degree 4. Store the result in a This code defines the file name for the electricity usage data.
variable named ind_predictedusage.
filename_res = 'elec_res.csv';
Do not modify the
variable res_predictedusagecreated in the Task 1 and Task 2
previous task. Modify the function call
predictdate1 = datetime(2019,07,01);
res_predictedusage =
polyPrediction(filename_res,predictdate1,2);

filename_ind = 'elec_ind.csv';
predictdate2 = datetime(2020,01,01);
ind_predictedusage =
polyPrediction(filename_ind,predictdate2,4);

Task 1
Modify the function definition
function predictedusage =
polyPrediction(filename,predictdate,degree)
% Import data
data = readtable(filename);
dates = data{:,1};
usage = data{:,2};
sector = data.Properties.VariableNames{2};

% Fill in the missing values.


usage = fillmissing(usage,'spline');

% Fit polynomial and predict usage for a future date.


elapsedYears = years(dates-dates(1));
c = polyfit(elapsedYears,usage,degree);

endDuration = years(predictdate-dates(1));
usageFit = polyval(c,elapsedYears);
predictedusage = polyval(c,endDuration);

% Plot the predicted usage.


plot(dates,usage,'o-')
hold on
plot(dates,usageFit,'LineWidth',2);
plot(predictdate,predictedusage,'*r');
hold off
xlabel('Date')
ylabel('Usage')
title([sector ' usage'])
end
15.3 Function Files: (1/7) Introduction
Introduction: Function Files In many situations, it is useful to create a function
Functions that are defined inside a MATLAB script that is accessible from outside of the script file. In
file (called local functions) can be accessed only by this lesson, you will learn to create functions that
the script in which they live. can be called from the Command Window, scripts,
and other functions.
You can run the script
which calls the local
function defined in the
script.

However, when you try to


call the local function from
the Command Window an
error is generated.
Similarly, the local
function cannot be called
from other scripts.

The function defined in


the script file is not visible
outside of the script.
15.3 Function Files: (2/7) Creating Function Files
To create a function that is accessible from the Command Window and other script and function files:

Step 1 - Create a new code file.


The file must have the same name as the function to
create.

Step 2 - Define the function


The function should be defined on the first non-
comment line of the file.
The function name should be same as the file name.
Step 3 - Write the function body
In function files, the end keyword is optional.

15.3 Function Files: (3/7) Calling Function Files


Calling Function Files
If you try to use the 'Run' button to execute the code in a function file, you will get an error because the
input arguments will not be assigned any value.

To run the function, you should call the function with the necessary input arguments from the Command
Window or from another function or a script.

15.3 Function Files: (5/7) Compare Using a Tolerance


he MATLAB TASK
function isequal compares Write a function named isequal_tol which takes three scalar inputs, x, y, and a
two arrays and returns true if tolerance tol. 
they are identical
and false otherwise.  It should return true if x and y differ by a number less than tol and false otherwise

In some situations, two


function out = isequal_tol(x,y,tol)
numbers which are slightly
different could be treated as if (abs(x-y) < tol)
'close enough' for the out = true;
purposes of a particular else
application. For example, a
variable x with value 2.1 and out = false;
another variable y with value end
2.100000009 differ by a small end
value on the order of 10-9.

15.3 Function Files: (6/7) Custom Statistics


The function file myStats.mlx contains the following function TASK
definition. Call the function myStats from the script to calculate
function [a,b,c,d] = myStats(x) the mean of the vector z and save it to a variable
a = mean(x); named myMean.
b = std(x);
c = median(x);
myMean = myStats(z)
d = mode(x);
end
The median is the third output returned by myStats. [~,~,myMed,~] = myStats(z)
TASK
Call the function myStats to calculate the median of the
vector z and save it to a variable named myMed.

The standard deviation is the TASK


second output returned Call the function myStats calculate the standard deviation and mode of the vector z.
by myStats, and the mode is Save the results to variables named myDev and myMode, repsectively.
the fourth.
[~,myDev,~,myMode] = myStats(z)

15.4 Workspaces: (1/6) Introduction


MATLAB scripts share the base workspace, i.e., they can read or modify any variables in the base workspace.
A function has its own workspace, separate from the base workspace. 

Using functions creates fewer variables in the base workspace, which results in fewer variable name conflicts. This
lesson focuses on function workspaces.
Suppose you have three
scripts.

When you run the first


script, the variables defined
in the script are stored in
the base workspace.
When you run the second
script, more variables are
added to the base
workspace. At the same
time, existing variables can
be modified.
As you run more scripts,
more variables accumulate
in the base workspace, and
the chances of conflicting
variable names increase.
15.4 Workspaces: (6/6) Summary

15.5 MATLAB Path and Calling Precedence: (1/7) Introduction


Introduction: MATLAB Path and Calling Precedence
A large application can have a number of MATLAB script, function, and data files. How can you organize
these files?
These files can access each
other and can also be used
from the Command
Window when the current
directory is set to that
particular folder.

As the number of files


increases, it is difficult to
manage all the files in a
single folder. Another
option is to organize the
files in separate folders.

Here, the current folder is


the folder named 'Data
Files'. Since you can only
refer to files in the current
folder, calling a MATLAB
function stored in a
different folder produces an
error.

Another option is to add


these folder's to MATLAB's
search path which is the
topic of this lesson.

15.5 MATLAB Path and Calling Precedence: (2/7) Adding Folders to MATLAB Path
Adding Folders to MATLAB Path
The search path, or path is a subset of all the folders in the file system. MATLAB can access all files in the
folders on the search path.
To add folders to the search path:
On the Home tab, in the Environment section, click Set Path.
Add a single folder or a set of folders using the buttons highlighted below.

15.5 MATLAB Path and Calling Precedence: (3/7) Calling Precedence


Calling Precedence Suppose you use a variable named date to store the
Using functions reduces the possibility of variable date of the first observation from the electricity data.
name conflicts. However, you can still have
conflicts if a user-created function has tjhe same
name as a built-in MATLAB function or if a variable
has the same name as a function.

elecData = readtable('elec_res.csv');
date = elecData.Dates(1)
date =
01-Jan-1990
However, MATLAB has an in-built function also
named date that returns a character vector
containing today's date.

Now, if you try to use date, will MATLAB refer to


the variable in the Workspace or the function
named date?

nextDate = date + 1
?
n MATLAB, there are rules for interpreting any elecData = readtable('elec_res.csv');
named item. These rules are referred to as the
date = elecData.Dates(1);
function precedence order. Most of the common date =
reference conflicts can be resolved using the 01-Jan-1990
following order:
nextDate = date + 1
nextDate =
Variables 02-Jan-1990
Functions defined in the current script
Files in the current folder
Files on MATLAB search path

A more comprehensive list can be found here.


So, in the example shown above, the variable date
is used instead of the function date
Which of the following has the
highest calling precedence?
File in the current directory
Variable in the local
workspace
File on the MATLAB path

Which of the following has the


lowest calling precedence?
File in the current directory
Variable in the local
workspace
File on the MATLAB path

(T/F) When you enter the Hint  – Only directories on the MATLAB path will be searched.
command 
myFunction
MATLAB will always search
your entire computer for a file
named myFunction.
True
False

15.5 MATLAB Path and Calling Precedence: (7/7) MATLAB Calling Precedence
TASK
Create a variable named sum with value equal to 5.
Sum = 5
You just created a variable named sum. However, TASK
MATLAB also has a build-in function named sum. Use the which command to determine whether the
function sum or the variable sum has the higher priority.
You can use the which function to determine which file (Do not save to a result.)
or variable with a given name has the highest priority in
the current context.
which sum

which name
It is possible to have multiple functions that are stored in TASK
different folders but have the same name. You can also Display the file location for all instances of items called sum.
use the which function to see all the files and/or (Do not save the result.)
variable on MATLAB's search path with a given name. which sum -all

which name -all

Clear the variable sum from the workspace. clear

15.6 Project - Functions


In this project you will produce a function which TASK
calculates the nth pyramid number. The nth pyramid Enter the function declaration for a function
number, P(n), represents the number of blocks in named pyramid which takes one input and produces one output.
a pyramid made from an n-by-n square of blocks
at the base, an (n-1)-by-(n-1) square on top of Note: Enter only one line of code declaring the function.
that, and so on. 

It can therefore be calculated as 


function P = pyramid(n)

 
Therefore, the first four pyramid numbers, for
example, are:
P(1) = 1
P(2) = 1 + 4 = 5
P(3) = 5 + 9 = 14
P(4) = 14 + 16 = 30

Remember, the formula to calculate TASK


the nth pyramid number, P(n), is  Edit the function code such that it returns as the output the
pyramid number of the input.

function P = pyramid(n)
P = sum((1:n).^2);
End
TASK Khufu = pyramid(210)
The Pyramid of Khufu, also known as the Great
Pyramid of Giza, is estimated to have had 210
stone layers when it was originally built. 

Estimate the number of blocks used to construct


the pyramid by calculating the pyramid number
of 210. You can do this by calling the
function pyramid from the script callpyramid.

Store your result in a variable called Khufu.

Vous aimerez peut-être aussi