Script, Function &
Debugging
Susovan Jana
Department of Information Technology
Institute of Engineering & Management, Kolkata, INDIA
Email (O): [email protected]
Email (P): [email protected]
2
What is a Script?
The simplest type of MATLAB® program is called a script.
Scripts are the simplest kind of program file because they
have no input or output arguments.
A script is a file that contains multiple sequential lines of
MATLAB commands and function calls.
They are useful for automating series of MATLAB
commands, such as computations that you have to
perform repeatedly from the command line or series of
commands you have to reference.
You can run a script by typing its name at the command
line.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
3
How to Create a Script
Click on “New Script” Button
Or
Click “New” dropdown menu &
select “Script” from the menu
Or
Press Ctrl+n
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
4
Blank Script
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
5
Saving a Script
Click on Save button or
press Ctrl+s
The file extension will
be .m
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
6
Saving in a Specific Location
Browse the location &
click on “Save” button
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
7
Writing & Running Simple Script
demo.m
x=5;
y=10;
sum=x+y;
disp(sum);
Run the script by
clicking on “Run”
button
Or
Type the script
name in the
command window
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
8
Script Editor
Compare
Print
Search Files
Navigation
─ Forward
─ Back
─ Jump to a line
─ Find by text
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
9
Compare two Scripts
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
10
Script Editor Insert Insert
Function
Warp
Comments
Section (Ctrl +j)
Insert Smart Increase Decrease Uncomment
Comment Indent Indent Indent (Ctrl+t)
(Ctrl+r) (Ctrl+i) (Ctrl+]) (Ctrl+ [)
Insert new section by %%
Make a line as comment line by inserting % symbol at
the beginning of the line
Single Indent takes 4 consecutive blank spaces
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
11
Section
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
12
Function
Syntax for function creation
function [<output parameters>] = <name of function>(<input parameters>)
Function Body
end
Saving
─ In a function file which contains only function definitions. The name of the file must match the
name of the first function in the file.
─ In a script file which contains commands and function definitions. Functions must be at the end
of the file.
─ Script files cannot have the same name as a function in the file. Functions are supported in
scripts in R2016b or later.
─ use the end keyword to indicate the end of each function in a file. The end keyword is required
when:
─ Any function in the file contains a nested function.
─ The function is a local function within a function file, and any local function in the file uses the end
keyword.
─ The function is a local function within a script file.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
13
Example of Function with One Output
Open a new function & write the below code
function total=addition(val1, val2)
total=val1+val2;
end
Save it as addition.m
Calling Function
─ result=addition(5, 2)
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
14
Example of Function with Multiple Output
calculator.m
function [addition, subtraction, multiplication, division] = calculator(val1,val2)
addition = val1 + val2;
subtraction = val1 - val2;
multiplication = val1 * val2;
division = val1 / val2;
end
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
15
Function in a Script File
Including functions in
scripts requires MATLAB®
R2016b or later.
Run as usual like a script
functioninascript.m
length=5;
width=2;
result=calarea(length, width);
disp(result);
function area_out = calarea(l, w)
area_out=l * w;
end
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
16
Multiple Functions in a Function File
calvolume.m
function volume_out = calvolume(length, width, height)
volume_out=calarea(length, width)*height;
end
function area_out = calarea(l, w)
area_out=l * w;
end
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
17
Inline Function
Syntax
─ f = inline(expr)
Constructs an inline function object
from the MATLAB® expression
contained in expr.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
18
Argument Specified Inline Function
If inline does not return the
desired function variables or if
the function variables are in the
wrong order, you can specify
the desired variables explicitly
with the inline argument list.
─ f = inline(expr,arg1,arg2,…,argN)
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
19
feval Command
Evaluate function
─ Calling once with different inputs
─ Gives output for corresponding inputs
─ The feval function follows the same
scoping and precedence rules as
calling a function handle directly.
Syntax
─ [y1,...,yN] = feval(fun,x1,...,xM)
Examples
─ x = feval('sum',[2 3 4])
─ [x y] = feval('round',[2.56, 3.47])
─ [x y] = feval('round',[2.56, 3.47],1)
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
20
Comparison between Script & Function
Both scripts and functions allow you to reuse sequences of
commands by storing them in program files. Scripts are the simplest
type of program, since they store commands exactly as you would
type them at the command line. However, functions are more
flexible and more easily extensible.
Scripts are m-files containing MATLAB statements. MATLAB
“functions” are another type of m-file. The biggest difference
between scripts and functions is that functions have input and
output parameters. Script files can only operate on the variables
that are hard-coded into their m-file. As you can see, functions
much more flexible. They are therefore more suitable for general
purpose tasks that will be applied to different data.
Scripts are useful for tasks that don't change. They are also a way to
document a specific sequence of actions, say a function call with
special parameter values, that may be hard to remember.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
21
Comparison between Script & Function
All variables created in the script are added to the workspace
for the current session. Furthermore, if any of the variables in
the script file have the same name as the ones in your current
workspace, the values of those variables in the workspace are
changed by the actions in the script. This can be used to your
advantage. It can also cause unwanted side effects.
In contrast, function variables are local to the function. (The
exception is that it's possible to declare and use global
variables, but that requires and explicit action by the user.)
The local scope of function variables gives you greater
security and flexibility. The only way (besides explicitly
declared global variables) to get information into and out of
a function is through the variables in the parameter lists.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
22
Debugging a MATLAB Program
You can debug your MATLAB® program interactively in
the Editor or programmatically using debugging
functions in the Command Window. Both methods are
interchangeable.
Before you begin debugging, make sure that your
program is saved and that the program and any files it
calls exist on your search path or in the current folder.
─ If you run a file with unsaved changes from within the Editor, then
the file is automatically saved before it runs.
─ If you run a file with unsaved changes from the Command
Window, then MATLAB software runs the saved version of the file.
Therefore, you do not see the results of your changes.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
23
Debugging a MATLAB Program
Set Breakpoint
Run File
Pause a Running File
Find and Fix a Problem
─ View or Change Variable While Debugging
─ Modify Section of Code While Debugging
Step Through File
End Debugging Session
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
24
Setting Breakpoints
Set breakpoints to pause the
execution of a MATLAB file so you can
examine the value or variables where
you think a problem could be. You
can set breakpoints using the Editor,
using functions in the Command
Window, or both.
To add a standard breakpoint in the
Editor, click the breakpoint alley at an
executable line where you want to
set the breakpoint.
Executable lines are indicated by a
dash ( — ) in the breakpoint alley.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
25
Run the File
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
26
Function Call Stack: Called Function
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
27
Function Call Stack: Script
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
28
Function Call Stack: Base
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
29
Pause a Running File
To pause the execution of a program while it is
running, go to the Editor tab and click the Pause
button. MATLAB pauses execution at the next
executable line, and the Pause button changes to a
Continue button. To continue execution, press the
Continue button.
Pausing is useful if you want to check on the progress
of a long running program to ensure that it is running
as expected.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
30
Find and Fix a Problem
While your code is
paused, you can
view or change
the values of
variables, or you
can modify the
code.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
31
Step Through File: Debugging Actions
Description Toolbar Button Function Alternative
Continue execution of file until the line where the Run to Cursor None
cursor is positioned. Also available on the context
menu.
Execute the current line of the file. Step dbstep
Execute the current line of the file and, if the line is a Step In dbstep in
call to another function, step into that function.
Resume execution of file until completion or until Continue dbcont
another breakpoint is encountered.
After stepping in, run the rest of the called function Step Out dbstep out
or local function, leave the called function, and
pause.
Pause debug mode. Pause None
Exit debug mode. Quit Debugging dbquit
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
32
End Debugging Session
After you identify a problem, end the debugging session
by going to the Editor tab and clicking Quit Debugging.
You must end a debugging session if you want to
change and save a file, or if you want to run other
programs in MATLAB.
After you quit debugging, pause indicators in the Editor
display no longer appear, and the normal >> prompt
reappears in the Command Window in place of the K>>.
You no longer can access the call stack.
If MATLAB software becomes nonresponsive when it
pauses at a breakpoint, press Ctrl+c to return to the
MATLAB prompt.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
33
Breakpoints
Setting breakpoints pauses the execution of your MATLAB®
program so that you can examine values where you think a
problem might be. You can set breakpoints using the Editor or
by using functions in the Command Window.
You can set breakpoints only at executable lines in saved files
that are in the current folder or in folders on the search path.
You can set breakpoints at any time, whether MATLAB is idle
or busy running a file.
There are three types of breakpoints:
─ Standard breakpoints
─ Conditional breakpoints
─ Error breakpoints
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
34
Standard Breakpoints
A standard breakpoint pauses at a specified line in
a file.
To set a standard breakpoint click the breakpoint
alley at an executable line where you want to set
the breakpoint. The breakpoint alley is the narrow
column on the left side of the Editor, to the right of
the line number. You also can use the F12 key to
set the breakpoint.
If you attempt to set a breakpoint at a line that is
not executable, such as a comment or a blank
line, MATLAB sets it at the next executable line.
To set a standard breakpoint programmatically,
use the dbstop function. For example, to add a
breakpoint at line 2 in a file named demo.m, type:
dbstop in demo at 2
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
35
Debugging : Step 1
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
36
Debugging : Step 2
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
37
Debugging : Step 3
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
38
Debugging : Step 4
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
39
Conditional breakpoints
A conditional breakpoint causes MATLAB to pause at a
specified line in a file only when the specified condition is met.
Use conditional breakpoints when you want to examine results
after some iterations in a loop.
To set a conditional breakpoint, right-click the breakpoint
alley at an executable line where you want to set the
breakpoint and select Set/Modify Condition.
A yellow, conditional breakpoint icon appears in the
breakpoint alley at that line.
Programmatically:
─ dbstop in <program name> at 6 <condition>
─ dbstop in conditional_breakpoin at 2 if age<=0
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
40
Adding Conditional breakpoints
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
41
Error breakpoints
An error breakpoint causes MATLAB to pause program
execution and enter debug mode if MATLAB encounters
a problem.
Unlike standard and conditional breakpoints, you do not
set these breakpoints at a specific line in a specific file.
When you set an error breakpoint, MATLAB pauses at any
line in any file if the error condition specified occurs.
MATLAB then enters debug mode and opens the file
containing the error, with the execution arrow at the line
containing the error.
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
42
Adding Error breakpoints
To set an error breakpoint, on the Editor
tab, click Run and select from these
options:
─ Pause on Errors to pause on all errors.
─ Pause on Warnings to pause on all warnings.
─ Pause on NaN or Inf to pause on NaN (not-a-
number) or Inf (infinite) values.
Programmatically
─ dbstop if error
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA
43
Susovan Jana, Department of Information Technology, IEM, Kolkata, INDIA