Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

16.

1 Course Example - Debugging: (1/2) Troubleshooting Code


Troubleshooting Code
When writing programs consisting of several commands,
coding errors or mistakes are inevitable.

As a result, MATLAB will generate error messages when those


programs are run.

There are two types of errors that you will see when you
program: syntax errors and run-time errors.

In this lesson, you will learn to use tools that help identify the
cause of syntax and run-time errors.
16.2 Code Analyzer: (1/5) Introduction
Introduction: Code Analyzer

Suppose you call the function getTopN from the Command


Window.

>> v = [12 5 -2 15 99 87 0 -9 8];


>> t2 = getTopN(v,2);
Suppose you call the function getTopN from the Command Error: File: getTopN.mlx.m Line: 2
Window. MATLAB displays an error message indicating that on Invalid expression. Unbalanced or
line 2, there is an unbalanced parenthesis. unexpected
parenthesis or bracket.

Let's fix the error and call the function again.


Another error message is generated because of a typing
mistake in the variable name sortedv.

You can call the function and fix these errors one at a time. A
better approach is to use the MATLAB Code Analyzer, which
identifies syntax errors in a script or function before you Undefined function or variable 'sortedv'.
execute code.
Error in getTopN (line 3)
topN = sortedv(1:N);
16.2 Code Analyzer: (2/5) Using Code Analyzer
Let’s look at the
function polyPrediction.
Does the code have any
errors?

Even before calling the


function, you can see that
the code has syntax errors.
The MATLAB Code Analyzer
indicates this by a small red
icon in the top right hand
corner of the Live Editor.

The Live Editor also shows


colored indicator lines
identifying the lines of code
that have errors.

Hover over the red


indicator line to see a
description of the error.
From the description, it
appears that a closing
parenthesis is missing.
Click on the line to scroll to
the location of the error,
highlighted with a red
underline.

Adding the parenthesis gets


rid of the red underline,
and thus the syntax error
from that line.

Notice that the message


indicator is now orange.
This means that there are
no syntax errors but the
Code Analyzer has warnings
for unexpected behavior or
opportunities for improving
the performance.
Hover the cursor over the
orange indicator line to see
the warning. From the
description, the code
creates a variable usagefit
but its value isn't used
anywhere else.

Click on the line to scroll to


the location of the warning,
highlighted with an orange
underline. Do we need to
define usagefit, or can we
remove it?

It appears the variable


name is spelled differently
later in the code. Here, the
warning indicator helped in
detecting an error.
Correcting this mistake gets
rid of the warning message.

Now the code is free of any


syntax errors or warnings.

16.2 Code Analyzer: (4/5) Remove Code Analyzer Warnings


Summary

16.3 Debugging Run Time Errors: (1/4) Introduction

Introduction: Debugging Run-Time Errors


Removing syntax errors from your code does not mean that the code is error free.
Consider the function call which produces the pUsage = predictUsage(data,pDate,3);
run-time error shown. Error using polyval (line 67)
Inputs must be floats, namely single or double.
It can sometimes be difficult to understand why
the error occurred without knowing the Error in predictUsage (line 10)
broader context such as the variable values. usagePred = polyval(c,endDuration);

In this lesson, you will learn how to use the


MATLAB debugger to investigate and resolve
errors such as this.
Debugging Run-Time Errors
Let’s call the
function predictUsage at
the command line.

MATLAB displays an error


message, which contains
the line number of the
command which generated
the error.

Click the line number, and


the Editor opens the file to
that line of code.

To investigate the error, you


can halt the code's
execution at any line and
look at the state of the
program just before that line
was executed.

These lines where


execution is halted are
called breakpoints. You
can set a breakpoint by
clicking the line number.

When you call the function


again, the program pauses
at the first breakpoint.

The function's workspace is


now visible in the
Workspace browser.
You can use the controls in
the Run section of the Live
Editor tab to control
execution.

The Step button runs the


current line of code,
advancing execution by one
line.

The Continue button


continues the execution to
the next breakpoint.

The Continue button


continues the execution to
the next breakpoint.
It appears
that endDuration is a
duration variable, but
the polyval function only
accepts numeric inputs.

To fix this error, you can


convert endDuration to a
numeric value using
the years function.

You can test your solution


in the Command Window to
see if it resolves the error.

It doesn't produce the error,


so you've identified the
change you need to make.

Now you can modify your


code and save the file. Click
the Stop button to end your
debugging session.
Before calling your function,
clear the breakpoints so the
execution doesn't get halted
again. To clear a
breakpoint, right-click the
breakpoint and select Clear
Breakpoint. To clear all the
breakpoints in the function,
select Clear All
Breakpoints in File.

Call the function from the


again – no error is
produced, and the correct
result is generated.

Summary: Debugging Run-Time Errors


When debugging MATLAB code, a common workflow is as follows.
Note that after you've identified and fixed any bugs, you should stop your debugging session, save your changes, and
clear all breakpoints before running your code again.

16.4 Project - Troubleshooting Code


TASK filename_ind = 'elec_ind.csv';
The code file shown ind_pred = polyPrediction(filename_ind,datetime(2020,1,1),2);
contains a couple of syntax function predictedusage =
errors. Use the Code polyPrediction(filename,predictdate,degree)
Analyzer messages to fix % Import data
these errors so that the data = readtable(filename);
script runs and returns the
dates = data{:,1};
predicted electricity usage
usage = data{:,2;
value.
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'])

You might also like