%% Basic debugging in Matlab
% If you're working with code in virtually any language, it's a good idea to become familiar with the basic debugging commands.  When you're getting errors, turn on the debugging and dive into what might be causing them.  Depending on the code, it's most often:
% 1 - Passing variables into the functions in an incorrect way (either in the wrong format or with invalid values)
% 2 - Attempting to call functions not on your Matlab path
%
%% Debugging and Analysis
%
%
%% Conditional debugging commands
% In Matlab, there are a set of these. They are super useful, and often start with “db”, and are:

dbstop
dbstack
dbup
dbdown
dbclear

% For example, if you're running some code and get errors, try:

dbstop if error

% This will allow you to run your code and stop inside the function if there is an error.
% Now run your code, and when the error occurs, you’ll get a

K>> 

% prompt.  You’re inside the function.
% Type:

dbstack

% …to see where you are in a series of potentially nested sub functions. This is the "stack". You call a function from the command line, which is the "top level". That calls another function (2nd level), which calls another function (3rd level), and so forth.
% Now, you can examine the variables within the function. e.g.,

whos

% will list which variables are in the workspace.
% Now isolate the line with the error, and you can check why it's not running properly. The most common issue is that the type of input variable or values of the input variable are invalid. This often happens when a higher-level calling function passes in the wrong variable type or values (e.g., an empty value, when a number is required).
% This can even happen when you pass in the wrong time of input variable to the top-level  function you called (what you typed on the command line). In this case, it's a problem with the user input, not the code, though debug mode can help you find out what the code expects internally and therefore what you did wrong.
% If you're inside an internal matlab function, that's unlikely to be buggy -- other functions probably passed in bad values. so type

dbup
dbstack

% to go up a level to the function that called the one in which the error was generated, and see where you are in the stack.
% You can navigate through the stack with dbup and dbdown, and check where you are using dbstack.
%% Setting breakpoints
% You can also set breakpoints in the in the Matlab editor before you run the functions. You do this by clicking on the -- next to the line number at which you want to set a breakpoint. A red circle appears, which means that execution will pause, and you'll get the K>> prompt to let you examine the variables inside subfunctions.
%% Clearing breakpoints and debug commands
% When you understand the error and have fixed it -- and thus you're done debugging -- you can use dbclear all to stop the debug mode.
%
%