Debugging in Matlab C. Reed 4/5/11 Bugs Debugging is a natural part of programming: Three standard types of errors: – Syntax errors: you simply have typed an illegal expression, independent of the values of the variables in the expression. – Run-time errors: logic errors that result in an illegal expression for specific values of the data (harder to fix) – Logic errors that result in the program executing completely, but the answer that they return is incorrect (hardest to fix). Syntax Error Example An M-file contains: x = 7; y = 8; if x = y x = y$2 else x = y(3 end Running at the command prompt gives: >> temp ??? Error: File: C:\Programs\MATLAB6p5\work\temp.m Line: 3 Column: 6 Assignment statements do not produce results. (Use = = to test for equality.) Syntax Error Analysis • Matlab only reported the first error it found. • It gives you a link to the position in the files where the error occurred. • It tells you what type of error (assignment statements do not produce results). • And it suggests a fix (use == to test for equality). Runtime Errors x = [1 2 3 4]; y = magic(2); % subtraction will cause an error - x is 2-D. xn = x – y; ??? Error using ==> minus Matrix dimensions must agree. Error in ==> temp at 4 z = x - y; Runtime Error Analysis • Matlab gives the line number that caused the error (sometimes errors can propagate) – Also gives the reason for the runtime error! • Runtime errors can often times be found manually – harder problems rely on the debugger Logic Errors %print odd numbers from 1 to 10 for i = 1:10 if rem(i,2) == 0 disp(i); end end Simple example, but can be very hard to track down Good debugging techniques come in handy here Debugger Example • type modes • type edit modes • use breakpoints to walk through code – try the keyboard command Handling Errors Yourself • try-catch: – http://www.mathworks.com/help/techdoc/ref/cat ch.html Decent Debugging Tutorials • http://www.youtube.com/watch?v=9iTj-Q6ZRE • https://engineering.purdue.edu/ECN/Support /KB/Docs/DebuggingMatlabMfile Additional Resources https://ceprofs.civil.tamu.edu/ssocolofsky/engr111a/Downloads/Lectures/Class%201 2.1%2004c%20Version%20A.ppt http://jagger.berkeley.edu/~pack/e77/Debugging.ppt