0% found this document useful (0 votes)
108 views

Lecture 11 - Functions

The document discusses functions in MATLAB. It explains that functions take inputs, perform operations, and return outputs. It distinguishes between core MATLAB built-in functions, MATLAB-supplied M-file functions created by MATLAB, and user-created M-file functions. It also describes how each function call has its own independent workspace. Functions provide modularity and allow breaking problems into smaller independent pieces of code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views

Lecture 11 - Functions

The document discusses functions in MATLAB. It explains that functions take inputs, perform operations, and return outputs. It distinguishes between core MATLAB built-in functions, MATLAB-supplied M-file functions created by MATLAB, and user-created M-file functions. It also describes how each function call has its own independent workspace. Functions provide modularity and allow breaking problems into smaller independent pieces of code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 17

MATLAB

Function
Functions

• Functions describe subprograms


–Take inputs, generate outputs
–Have local variables (invisible in global workspace)

• Core MATLAB (Built-in) Functions


–sin, abs, exp, ...
Can’t be displayed on screen

• MATLAB-supplied M-file Functions


–mean, linspace, …
Ca be displayed on screen

• User-created M-file Functions


Core MATLAB (Built-in) Functions

• Elementary built-in functions


• >> help elfun % a list of these functions
sin % Sine.
exp % Exponential.
abs % Absolute value.
round % Round towards nearest integer.
• Special Math functions
• >> help specfun
lcm % Least common multiple.
cart2sph % Transform Cartesian to spherical
% coordinates.

• Special functions - toolboxes


• Each toolbox has a list of special functions that you can use
Function Is an Independent Piece of
Code Which Performs a Task

Function (subroutine, method,


procedure, or subprogram) –
is a portion of code within a
larger program,
which performs a specific task
and
can be relatively independent
of the remaining code.

One M-file, One Task, One Workspace


4
Variables - The Data Objects,
Functions Are The Actions
Input (Object / Data):
X = 80 90 95 100 98 88 92
Functions:

y = mean(x) y = sum(x) y = max(x)


Output:
(Data)
91.85 643 100
5
A Function Is a Black Box

Output function Input

A function is a black box


It hides the code and its workspace and
communicates with the “world” using
the input and output variables
6
Functions M file structure

The file is a Matlab function


The output variables (if there are few use []: [out1 out2] )
Should be same as the name of the file
sumTwoNums.m:
function my_sum = sumTwoNums(a,b)

my_sum = a+b;

Assign the output variables The input variables


(else - Matlab will give an error)
7
Functions Documentation and Variable
Verification
function my_sum = sumTwoNums(a,b)
% SUMTWONUMS sum to scalars First line
help: % this function sums two scalar
% and returns the result
Usage % INPUT:
% a - the first scalar
Input % b - the second scalar
%
Output % OUTPUT:
% my_sum - the sum of a and b; sum = a+b
Examples
if (~isscalar(a))
Testing for error('First argument is not a scalar');
proper end
if (~isscalar(b))
variables error('Second argument is not a scalar');
end
8 Calculations and Output assignment
my_sum = a+b;
Each Instance of A Function Run Has
Its Own Workspace
Assume we wrote the function:
function my_sum = sumTwoNums(a,b)
my_sum = a + b;

In the workspace we run: Matlab Function


Workspace:
a = 1; Workspace:
b = 2; a=3
x = 3; a=1
y = 4; b=4
s = sumTwoNums(x, y) b=2
 my_sum = 7
What is the output? x=3
s = 7
y=4
9
s=7
Structure of a Function M-file
Keyword: function Function Name (same as file name .m)
Output Argument(s) Input Argument(s)

function y = mean(x)
% MEAN Average or mean value.
% For vectors, MEAN(x) returns the mean value.
Online Help
% For matrices, MEAN(x) is a row vector
% containing the mean value of each column.
[m,n] = size(x);
if m == 1
MATLAB
Code m = n;
end
y = sum(x)/m;

»output_value = mean(input_value) Command Line Syntax


Workspaces in MATLAB
• MATLAB (or Base) Workspace:
– For command line and script file variables.
• Function Workspaces:
– Each function has its own workspace for local variables.
– Name of Input/output variables can be either equal or different
then the variable name in the calling workspace.
– Communicate to Function Workspace via inputs & outputs.
• Global Workspace:
Global variables can be shared by multiple workspaces.
(Must be initialized in all relevant workspaces.)

Initialize global variables in all relevant workspaces:


»global variable_name
Initialize global variables in the “source” workspace before referring to them
from other workspaces.
Tips for using Global Variables

• DON’T USE THEM

• If you absolutely must use them:


– Avoid name conflicts
>>whos global %shows the contents of the global
workspace
>>clear global %erases the variable from both local
and global workspaces.
Visual Debugging

Select
Workspace

Set Auto-
Breakpoints

Set Breakpoint
Clear Breaks
Step In
Single Step
Continue
Quit Debugging
Example: Visual Debugging (2)
• Editor/Debugger opens the relevant file and identifies the
line where the error occurred.

Current
Current
Location
Workspace
(Function)
Example: Visual Debugging (3)

Error message

Access to
Function’s
Debug Workspace
Mode
Problem

• Write a function that asks for a temperature (in degrees


Fahrenheit)
• computes the equivalent temperature in degrees Celcius.
• The function should give an error massage in case no
number is provided to convert.
• use nargin.
Solution

function TinC=temp2(TinF)
TinF = input('Temperature in F: '); % get input
if nargin==0 % if there is no input
disp('no temparture was entered');
TinC=nan;
else
TinC = 5*(TinF - 32)/9; % conversion
disp(' ')
disp([' ==> Temperature in C = ',num2str(TinC)])
disp(' ')
end

You might also like