Professional Documents
Culture Documents
T3 Functions
T3 Functions
Abstraction – Functions
(includes slides from Shanika Karunasekera)
Adrian Pearce
(adrianrp@unimelb.edu.au)
Overview
• Using functions
Functions
• Abstraction: the process of creating self-contained,
reusable, units of software with clearly defined units
called functions.
• Functions contain:
– inputs;
– outputs; and
– behaviour;
that can then be put together to solve complex problems.
MATLAB functions
• MATLAB functions have the following general usage syntax:
• function signature:
– The first line of the function is the function signature
– Contains the function name, input and output parameters
• function body:
– Contains commands for the function
– Input values (e.g. x1, x2) are used in commands within
the function body to compute output values (e.g. y1, y2)
% my_add_driver.m
clear all;
>> my_add_sub_driver
Enter the first number 6
Enter the second number 7
The sum of 6 and 7 = 13
The difference of 6 and 7 = -1
% my_add_driver_1.m
a = 5;
b = 6;
my_add_1(a, b)
fprintf('The sum of %d and %d = %d\n', a, b, y);
>> my_add_driver_1
Undefined function or variable 'y'.
Error in my_add_driver_1 (line 5)
fprintf('The sum of %d and %d = %d\n', a, b, y);
Engineering System Design 2 14 Melbourne School of Engineering
Abstraction - Functions
% my_test_driver.m
x1 = 5;
my_test(x1);
fprintf('Value of x1 = %d\n', x1);
>> my_test_driver
Value of x1 = 5
>> my_add_driver_2
c =
3 7 11
Function Design
function S = nybblise(x)
% encode a 16x1 vector x and splits it into a
% 4x4 matrix (four nybbles) S
% Fill me in!
end
function h = hamming_7_4(d)
% takes a nybble (four bit vector) and returns
% the associated Hamming (7,4) code
% (p1 p2 d1 p3 d2 d3 d4) h
% Fill me in!
end