Which of the following types of errors occur while a program is executing?

Syntax errors are mistakes in using the language. Examples of syntax errors are missing a comma or a quotation mark, or misspelling a word. MATLAB itself will flag syntax errors and give an error message. For example, the following character vector is missing the end quote:

>> mystr = 'how are you;

mystr = 'how are you;

 

Error: Character vector is not terminated properly.

If this type of error is typed in a script or function using the Editor, the Editor will flag it.

Another common mistake is to spell a variable name incorrectly; MATLAB will also catch this error. Newer versions of MATLAB will typically be able to correct this for you, as in the following:

>> value = 5;

>> newvalue = valu + 3;

Unrecognized function or variable 'valu'.

Did you mean:

>> newvalue = value + 3;

Runtime, or execution-time, errors are found when a script or function is executing. With most languages, an example of a runtime error would be attempting to divide by zero. However, in MATLAB, this will return the constant Inf. Another example would be attempting to refer to an element in an array that does not exist.

runtimeEx.m

% This script shows an execution-time error

vec = 3:5;

for i = 1:4

 disp[vec[i]]

end

The previous script initializes a vector with three elements, but then attempts to refer to a fourth. Running it prints the three elements in the vector, and then an error message is generated when it attempts to refer to the fourth element.

Note

MATLAB gives an explanation of the error, and it gives the line number in the script in which the error occurred.

>> runtimeEx

 3

 4

 5

Index exceeds array bounds.

Error in runtimeEx [line 6]

 disp[vec[i]]

Logical errors are more difficult to locate because they do not result in any error message. A logical error is a mistake in reasoning by the programmer, but it is not a mistake in the programming language. An example of a logical error would be dividing by 2.54 instead of multiplying to convert inches to centimeters. The results printed or returned would be incorrect, but this might not be obvious.

All programs should be robust and should, wherever possible, anticipate potential errors and guard against them. For example, whenever there is input into a program, the program should error-check and make sure that the input is in the correct range of values. Also, before dividing, any denominator should be checked to make sure that it is not zero.

Despite the best precautions, there are bound to be errors in programs.

Read moreNavigate Down

View chapterPurchase book

Read full chapter

URL: //www.sciencedirect.com/science/article/pii/B9780128154793000064

Errors and Pitfalls

Brian H. Hahn, Daniel T. Valentine, in Essential MATLAB for Engineers and Scientists [Sixth Edition], 2017

11.1 Syntax errors

Syntax errors are typing errors in MATLAB statements [e.g., plog instead of plot]. They are the most frequent type of error, and are fatal: MATLAB stops execution and displays an error message. As MATLAB evolves from one version to the next, error messages improve. Try the following examples to examine the latest error messages:

     2*[1+3

     disp[['the answer is ' num2str[2]]

There are many possible syntax errors—you will probably have discovered a few yourself. With experience you will become more adept at spotting your mistakes.

The function lasterr returns the last error message generated.

11.1.1 Incompatible vector sizes

Consider the following statements:

x = 0:pi/20:3*pi;
y = sin[x];
x = 0:pi/40:3*pi;
plot[x,y]

You'll get the error message

Error using ==> plot
Vectors must be the same lengths.

because you forgot to recalculate y after reducing the x increments. whos reveals the problem:

x         1x121          ...
y         1x61           ...

11.1.2 Name hiding

Recall that a workspace variable ‘hides’ a script or function of the same name. The only way to access such a script or function is to clear the offending variable from the workspace.

Furthermore, a MATLAB function hides a script of the same name, e.g., create a script called why.m that displays some junk message, and then type why at the command line.

If you are worried that a variable or script which you are thinking of creating, say blob, may be a MATLAB function, try help blob first.

Read moreNavigate Down

View chapterPurchase book

Read full chapter

URL: //www.sciencedirect.com/science/article/pii/B9780081008775000128

PIC16 C Applications and Systems

Martin P. Bates, in Programming 8-bit PIC Microcontrollers in C, 2008

Application Debugging and Testing

The application program is tested and debugged in several stages. The main types of errors and the tools for detecting them are outlined next.

Syntax errors are mistakes in the source code, such as spelling and punctuation errors, incorrect labels, and so on, which cause an error message to be generated by the compiler. These appear in a separate error window, with the error type and line number indicated so that it can be corrected in the edit window.

When the program is successfully compiled, it can be tested for correct function in the target hardware so that any logical errors can be identified. However, it is preferable to test it in software simulation mode first, as it is quicker and easier to identify errors in the program sequence. Two simulation methods are available here, MPSIM and Proteus VSM.

MPSIM is the simulator provided with MPLAB. It allows the program source code to be run, stopped and stepped, and breakpoints set. The registers and source variables may be inspected at each step. When debugging C programs, breakpoints are the most useful, while stepping is more useful in assembly language. The program sequence and variable values are monitored and errors identified when the results obtained do not agree with those expected. Error information is provided principally in tabular form.

By comparison, the Proteus VSM debugging environment has significant advantages. The animated schematic gives a much more immediate indication of the overall program function. Interactive input and output devices operate in real or simulated time. The source code and breakpoints can be displayed.

In addition, if the VSM viewer is run from within MPLAB, the progress of the program can also be monitored simultaneously in MPSIM. Therefore, the more detailed debugging tools in MPSIM can be run alongside VSM and the most appropriate selected for any debugging task. The simulated hardware design is thus tested in conjunction with the MCU firmware [cosimulation], allowing circuit modifications at an early stage and hardware-software interaction to be studied on screen. When the program is eventually downloaded to the real hardware, it is now far more likely that it will work the first time.

The VSM Viewer is invoked from the debug tools menu in MPLAB, and the program is attached and tested. However, if circuit modifications are needed, VSM must be opened separately to run alongside MPLAB, so that the full set of ISIS schematic edit tools and component models are available. VSM still accesses the same COF file, so both software and hardware changes can be tested. More details on interactive debugging are given in Appendices A, B, and CAppendix AAppendix BAppendix C.

Read moreNavigate Down

View chapterPurchase book

Read full chapter

URL: //www.sciencedirect.com/science/article/pii/B9780750689601000055

Program Development and Testing

Andrew P. King, Paul Aljabar, in MATLAB Programming for Biomedical Engineers and Scientists, 2017

4.4 Debugging a Function

The basics of the MATLAB debugger were described in Section 1.12. Here, we consider some of the types of errors that the debugger can be used to help identify and fix.

When writing a program or function that is non-trivial, the chances of it working perfectly first time are quite low, even for a skilled MATLAB user. Debugging tools are there to help identify why a program does not work correctly or as expected.

When debugging, we need to work systematically and run our program with various sets of test data to find errors and correct them when we find them. If we work incrementally as we did in Example 4.1 above, then the repeated nature of the testing allows errors to be caught earlier, which reduces the chance of later errors occurring or minimizes their severity.

There are three main types of error that a function or program can contain:

Syntax errors.

Run-time errors.

Logic errors.

The term ‘syntax’ relates to the grammar of the programming language. Each language has a specific set of rules for how commands can be written in that language and these rules are collectively known as the language's syntax.

When a line in a MATLAB function contains a syntax error, the built-in Code Analyzer [see Section 1.12.2] should highlight in red the corresponding line of code. Hovering the mouse over the line should result in a message being displayed to the user that describes what MATLAB has decided is the particular syntax error in the line. In other words, MATLAB can detect an error with the script or function before it is run.

Example 4.2 A syntax error

If the following code is entered into a script, say my_ script.m, using the editor, then the line containing the

statement should be highlighted in red to indicate a problem with the syntax.

This is because the syntax rules of MATLAB require a closing
statement for each
statement.

O4.C, O4.D

If we fail to notice this error and attempt to run the script from the command window, we will get an error when MATLAB reaches the relevant part of the code and a more dramatic message will be displayed:

   >> my_script

Clicking on the part of the error report with the line number will take us directly to the corresponding place in the script file so that we can figure out how to correct the error. In this case, adding an
statement after the
call should be enough.

Activity 4.2

Type the code from the previous example into a script. Confirm that the Code Analyzer highlights the error. Fix the error and confirm that the highlighting disappears.

O4.C, O4.D

Example 4.3 Another syntax error

The following code contains a syntax error. The MATLAB code analyzer should highlight it in red. The code begins by generating a single random number between 1 and 10 and then it seeks to decide if the random number equals three or not, adjusting its output in each case.

O4.C

Activity 4.3

Type the code from the previous example into a script. Confirm that the Code Analyzer highlights the error. Fix the error and confirm that the highlighting disappears.

O4.C, O4.D

The reason for this syntax error is that the

sign used in the
statement is an assignment operator and should not be used to test for equality. The correct symbol to use here is the comparison operator which is
in MATLAB, i.e. two equals signs, not one [see Example 2.2]. This is also the case in quite a few other languages and it is very common to mix up these operators.

Example 4.4 A run-time error

Some errors cannot be determined by MATLAB while we are editing the code and can only be found when the code is run. This is because a specific sequence of commands needs to be run to bring about the conditions for the error. Consider the following code in a script called someScript.m. It aims to generate three sequences of numbers and assign them to array variables

,
and
. Then it tries to find the sums of each of these sequences [line numbers have been shown here to help the description].

In this case, there are no syntax errors but running the script at the command window leads to a run-time error as follows:

   >> someScript
       55

      110

O4.C

Activity 4.4

Type the code from the previous example into a script. Run the script from the command window to reproduce the error.

O4.C

The problem with the code in Example 4.4 is related to the choice of variable names. The sums of the arrays

and
have been given sensible names [
and
]. The sum of the array variable
has been stored in a variable called
. This is a problem because the local script has used the name of a built-in MATLAB function as a name for a local variable.

Using the name of a built-in function for a variable that we use locally is called shadowing. We can check if a name is already used by MATLAB or in the workspace using the

command. In this case, we can trivially check

The return value of 5 indicates that the name

exists and is attached to a function [as opposed, say, to a file]. Type
at the command window for more details. We can check a more sensible name as follows:

The value of 0 returned indicates that the name

is not being used and we can safely use it in our code.

Returning to the code in Example 4.4, when the execution reaches line 13, the programmer's intention was to use the built-in MATLAB function called

, but this now refers to a local variable that contains a single number. The use of the brackets in line 13 is now interpreted as a request for an element or elements taken from an array called
. The elements requested are at the indices specified by another variable,
. That is, the indices requested start at 3 and go up to 30 in steps of 3. The problem however, is the variable called
is just a single scalar value, i.e. it as an array of length one. It is not possible to obtain an element from it at index 3 or higher. This is the reason for the code crashing at run-time.

Apart from giving an example of a run-time error this example shows why it is very important not to give names to variables that are already used to refer to built-in functions. MATLAB will not complain when you do this so be careful!

Example 4.5 A run-time error

Here is some more code that gives a run-time error:

In this case, when the code is run, the following output is given

   >> someScript

O4.C

Activity 4.5

Type the code from Example 4.5 into a script. Run the script from the command window to reproduce the error. Can you see why this error occurs?

O4.C

The script in Example 4.5 calls

at the start. This means that even if the workspace contained a global variable called
before calling the script, then it would have been cleared and would no longer be available. Hence, the request to calculate
will always fail as there is no variable called
. This would need to be defined before the point where the
function is called to make the code work [but after the
].

Activity 4.6

Fix the code from Example 4.5 by introducing an appropriate local variable and assigning a value to it. Run the script to check it works.

O4.D

Logic Errors

Logic errors can be some of the hardest to find, and identifying them often requires using the debugger to carry out careful line-by-line inspection of the code as it is running. This is because no error is reported by MATLAB and the Code Analyzer does not highlight anything either. However, when the code is run, an incorrect output or behavior results and MATLAB will generally not provide a clue as to why this happened.

Example 4.6 A logic error

In this example, the following code attempts to show that sin⁡θ=12when θ=30∘:

When we actually run the code, we get the following output with no error reported:

  >> someScript
  These should be equal: -0.99 and 0.50

O4.C

This shows two numbers that are clearly not equal so what has gone wrong?

Activity 4.7

Type the code from Example 4.6 into a script and run it to reproduce the same output.

O4.C, O4.D

Can you see why the output is incorrect? Place a breakpoint in the code and run the script again. Check the values of the variables to see if there is a clue.

To track down the reason for the behavior in Example 4.6 we need to carry out some further investigation. In the command window we can look at the help on the

function which we might suspect of being broken:

  >> help sin
   sin    Sine of argument in radians.
      sin[X] is the sine of the elements of X.

This shows that the built-in MATLAB trigonometric function

expects its argument in radians so that is what we should give it. The function when used above gave the correct result for the sine of 30 radians – not degrees. That is, there was a mismatch between our expectation of the function and what it was designed to do. This error is readily fixed in a number of ways, for example by replacing
with
where we have made use of the built-in MATLAB constant
.

Activity 4.8

Fix the code in Example 4.6 and confirm that sin⁡30∘does indeed equal 1/2!

O4.C, O4.D

Because no error message is given, logic errors can be difficult to detect. Sometimes we might not even notice that the program or function is behaving wrongly. Even when we suspect a logic error exists, by noticing something incorrect in the program's behavior, it can still be difficult to pinpoint where the error is. There is no error message helpfully pointing us to a specific line in the code, as in the case of syntax errors. Worse still, the error will not necessarily be restricted to just one line – it can arise from the way different sections of code interact.

The error in the previous example was due to the intention to use degrees where radians should have been used instead. This is only noticed by observing the actual values of the output and seeing that the numeric value is not correct; in other words, by careful inspection of the output.

One way to identify logic errors in a function is to use the MATLAB interactive debugger to step through the function line-by-line, perhaps with a calculator or pencil and paper to hand [see Section 1.12].

Another way is to take each line of the code and copy-and-paste it into the command window, executing each line at a time and assessing its result to see if it is right.

Putting lots of statements in the code that display output and the values of the most relevant variables using the

or
commands can also help. Values of variables can be displayed before and after critical sections of the code, e.g. calls to other functions or important control sections such as
clauses and
or
loops. Once we have checked and are satisfied that the function or program is working correctly, the extra output statements should be removed.

Read moreNavigate Down

View chapterPurchase book

Read full chapter

URL: //www.sciencedirect.com/science/article/pii/B9780128122037000045

PIC Program Development

Martin Bates, in PIC Microcontrollers [Third Edition], 2011

4.6.1 Syntax Errors

If there are any syntax errors in the source code, such as spelling, layout, punctuation or failure to define labels properly, error messages will be generated by the assembler. These will be displayed in a separate window, indicating the type of error and line number. The messages and line numbers must be noted, or the error file, BIN4.ERR, printed out then the necessary changes made to the source code. The error is sometimes on a previous line to the one indicated, and sometimes a single error can generate more than one message. Warnings and information messages can usually be ignored, and can be disabled. There are more details about error messages in Chapter 9.

You may receive the following messages:

 Warning[224] C:\MPLAB\BOOKPRGS\BIN4.ASM 65 : Use of this instruction is not recommended.

 Message[305] C:\MPLAB\BOOKPRGS\BIN4.ASM 81 : Using default destination of 1 [file].

The first warning is caused by the special instruction TRIS, which is not part of the main instruction set. It is a simple way of initializing the port, and there is an alternative method using register bank selection, which is preferred in real applications. This will be introduced later.

The message about the ‘default destination’ is caused by the simplified syntax used in these programs, where the file register is not explicitly specified as the destination in instructions where the result can be placed in either the file register or the working register. The assembler assumes that the file register is the destination by default, and we are taking advantage of this to simplify the source code.

When all errors have been eliminated and the program has been successfully assembled, the machine code can be inspected by selecting ‘View’, ‘Program Memory’. Note that the source code labels are not reproduced, as the program code has been ‘disassembled’ [recreated] from the machine code. That is, the hex file has been converted back to mnemonic form so that it can be checked against the original.

Read moreNavigate Down

View chapterPurchase book

Read full chapter

URL: //www.sciencedirect.com/science/article/pii/B9780080969114100047

MATLAB® Debugging, Profiling, and Code Indentation

Munther Gdeisat, Francis Lilley, in Matlab by Example, 2013

Lesson 8.1 MATLAB® Debugging

Objectives

To learn the differences between syntax errors and runtime errors.

To learn how to debug MATLAB script files.

To learn how to use the Breakpoint tool to debug MATLAB code.

To learn how to run one line of a program using the Step tool.

Topics

8.1.1

Syntax and Runtime Errors

8.1.1.1

Syntax Errors

8.1.1.2

Runtime Errors

8.1.2

Debugging MATLAB® Code

8.1.2.1

Setting Up a Breakpoint

8.1.2.2

Stepping Through the Program

8.1.1 Syntax and Runtime Errors

There are two types of errors that appear in MATLAB expressions: syntax errors and runtime errors. Together, we generically refer to these errors as being bugs in the MATLAB code. The debugging process is the procedure of finding these bugs and fixing them.

8.1.1.1 Syntax Errors

Let us start with the first error type, which is the syntax error. These errors mainly occur as a result of the misspelling of variable or function names or from missing quotes or parentheses [or the accidental extraneous typing of an additional one of these]. Examples of such errors are given below:

>>x=x*[1+2*x]];%extraparenthesis>>x=1;x=x[x+1]%Themultiplicationsignismissing>>y=‘hello%missingquote>>z=1;disp[Z];%MATLABiscasesensitive,soZisnotthe%sameasz.

Note that you can type more than one MATLAB command in a single line, but these commands should be separated by a comma [,] or a semicolon [;].

When you type a MATLAB command in the Command Window, MATLAB checks for syntax errors before running the command. If the command passes the syntax error check, then MATLAB executes this command; otherwise, MATLAB displays a message reporting that there is a syntax error and that it should be fixed before attempting to run this command again. Also, MATLAB may give you some information that helps in identifying and fixing this error.

Suppose that you attempt to run a MATLAB script file that contains syntax errors. MATLAB does not run this file and responds by reporting that the file contains syntax errors. It rather helpfully provides you with the line number that contains the first syntax error that it has found in the file, and it also advises you about how to fix this error.

8.1.1.2 Runtime Errors

Runtime errors are found by MATLAB during the execution of a program, and they are generally more difficult to fix than simple syntax errors. The ability to fix runtime errors is something that improves with experience and is best learned by way of an example.

Let us try to write a MATLAB program that calculates the absolute values of a vector. The input vector in this example consists of the integer values from −10 to +10. Hence as a result of calculating the absolute values of this vector, all the positive input values from the range −10 to +10 should be unchanged [and zero will also be unchanged] and all negative input values will have their negative signs removed, leaving just their magnitude, for example, the value −3 will become 3. that is, the input vector is

−10−9−8−7−6−5−4−3−2−1012345678910

which should produce an output vector as follows:

10987654321012345678910

Launch the MATLAB Editor. Type the code below into the Editor window. Save the script file with the name absolute.m.

It is advisable to start any MATLAB script file with the commands clear; clc;. These two respective commands delete any unwanted variables in the MATLAB memory and also clear the Command Window. The command close all closes all figures in MATLAB.

clear; clc; close all

x = −10:10;

for k = 0:length[x]

 if [x[k] > 0]

  x[k] = −x[k];

 end

end

disp[x]

Run the program. MATLAB complains that there are errors in the code. MATLAB reports the error as follows:

??? Attempted to access x[0]; index must be a positive integer or logical.

Error in ==> absolute at 4

 if [x[k] > 0]

MATLAB starts indexing any vector with the index 1. This is unlike several other programming languages, such as C, which start the indexing process with index zero. So, we have identified this runtime mistake, which must be fixed by changing the index in the third line [beginning for k =] from the current value of 0 to a value of 1, as shown in the following code segment:

clear; clc;

x = -10:10;

for k = 1:length[x]

 if [x[k] > 0]

  x[k] = -x[k];

 end

end

disp[x]

Fix the bug and run the program over again. MATLAB gives the results as shown in the following figure, which are not as expected. The numbers that are produced should all be positive, but they are not. So we need to fix this bug. and we will use MATLAB’s debugging capabilities to track down the location and exact nature of the bug.

8.1.2 Debugging MATLAB Code

8.1.2.1 Setting Up a Breakpoint

MATLAB has a feature that allows the user to control the execution of an M-file program. This feature helps in tracking down the bugs and fixing them. For example, you can introduce a Breakpoint in a program, and the execution of the code temporarily stops at this Breakpoint. Then you can check the values of the MATLAB variables at this point and try to figure out the cause of the bug.

To debug your program, go to the Editor window. Using the mouse, left-click in the space between the column of line numbers and the code itself [where there is a column of dashes “–”] and place the Breakpoint in the position pointed at by the arrow in the following diagram. A red circle then appears as shown. This can be toggled on and off by clicking again in the same place. If you practice toggling this here, make sure you leave the Breakpoint set to ON, with the red dot showing as in the following figure.

Go to the Menu→Debug→Run absolute.m.

Note that as a result of doing this, the MATLAB Command Prompt changes to

k>>

which informs you that MATLAB is now running in debug mode.

MATLAB starts executing the program and stops at line 1.

8.1.2.2 Stepping Through the Program

To direct MATLAB to run the command in line 1, click on the Step icon [pointed at by the arrow in the following figure].

MATLAB runs the first line and then proceeds to line 2.

An alternative way to step through the program is by pressing the F10 key on the keyboard. Press F10 to make MATLAB run line 2 of the code.

Move the mouse and place the cursor directly over the variable x. A yellow box pops up and tells you the values of x.

Alternatively, you can get the values of this vector variable by double-clicking on x in the Workspace window.

Press F10 to run line 3. Using the mouse, highlight the expression [x[k] > 0]. Place the mouse cursor over the highlighted area and right-click. Choose Copy from the Context Menu.

In the Command Window, right-click the mouse and choose Paste. Then press Enter on the keyboard. MATLAB evaluates the expression and informs us that it has a value of 0. In this manner you can determine the value of any expression or variable.

The value of the first element in the variable x is −10. Press F10. The code steps to line 7. It should have entered the if statement and gone to line 5 to change the sign of the first element, but it did not. Instead it went to line 7. By noting this, we can discover that there is a programming error in the condition for the if statement. The greater than character “>” should be changed to the less than character “” to “

Chủ Đề