Difference between script and matlab command window - matlab

I wonder what the difference is between entering a few lines in the command window, or letting a script execute them.
In the question Escape from nested try - catch statement I have an example function. I have put the selected code in a script and called it, however then it does not work properly. On the other hand, when I
select the lines and hit f9, it works as expected.
The lines are:
dbclear all
dbquit
dbstop if caught error
I call the example function as such:
dbstop if caught error
mytestmain
And the example function is:
function mytestmain
try
mytestsub
catch
end
% Definition of subfunction, may or may not be in the same .m file
function mytestsub
try
a=b; %Intentionally generate an error as b is not defined
catch
end

I think it's related to MATLAB's just-in-time (JIT) compiler, which compiles functions before it runs them.
It seems that it compiles functions differently if dbstop is set or not (see here for reference). As it currently stands, MATLAB can not recompile a function while it is run (just try saving a changed function during a dbstop, and you will get a message informing you). As you can add and remove breakpoints during a dbstop I think you can also do so programmatically, but it should be impossible to "turn on" debugging if it wasn't turned on at "compile time"
So in your cases:
Using F9 it's just pasted and parsed as if you input it manually. So first dbstop is set, then mytestmain gets compiled and executed.
Running as a script will first compile the script and mytestmain and then execute it - so dbstop would be set after compilation and therefore not in effect.

Depending on what you mean by "doesn't work", it could just be because the debugger is a special context and certain debugger commands - dbup, dbdown, and dbquit - only work when you're at a debugger "K>>" prompt. Once you call a script, you're no longer at the debugger prompt but in normal code execution - inside a nested M-code call stack - and they just don't work there. When you F9, it does the lines individually, so each one is done from the prompt.
As a workaround, if you really want to execute a sequence of debugger commands like this, you could write a little Java Swing widget to enter the text in to the command window just as though you were typing it in.

Related

Error Function definitions are not permitted in this context

I have these four lines written in a file called abc.m
function [x, y] = abc(q, r)
x=q;
y=r;
end
When I press CTRL+enter, I first get a popup that says
The selected section cannot be evaluated because it contains an invalid statement
Then in the command prompt it says:
function [x,y]=abc(q,r)
↑
Error: Function definitions are not permitted in this context.
I have read the other questions on this error, and I do not understand why this simple file wont work.
When you press, ctrl+enter, this is the equivalent of Run Selection which will execute a code block surrounded by %%'s. The code in this code block is run as a script which essentially copies and executes the lines of your code block one at a time in the command window. In all current versions of MATLAB, you cannot define a function within a script or directly within the command window, which is the cause for your error.
If you simply want to execute your function, you will want to use Run (or F5) to do so which will run the entire file, as a function.

Retrieve a variable from a function that crashed matlab

Is there a way to retrieve the output of a function that did not complete properly?
For instance, a (non global) variable that was correctly computed by a function but that couldn't be saved properly because of syntax errors.
In principle, you can't look into a function once the program has stopped with an error. (That's why I often try to avoid functions.)
However, you can achieve what you want by entering debugging mode, using the dbstop function to set a breakpoint:
The dbstop function is used to temporarily stop the execution of a
program and give the user an opportunity to examine the local
workspace.
In particular, typing
dbstop if error
in the command window before running your code will make it stop at the point that caused the error and look at the variables within that function.
To restore normal behaviour you need the dbclear function. Type
dbclear if error
to remove the previously set breakpoint, or
dbclear all
to remove all breakpoints.

How to set breakpoints in windbg that does not stop the execution of the program just logs the function called

I am debugging a windows component and want to view all the functions of a particular dll that are called (also in the exact order they are called). I can do this by attaching the component to windbg and setting breakpoints over all the exported functions (bm *module_name!*) of the dll in question.
This works as expected. Whenever an exported function of that dll is called windbg breaks the execution and prints on the screen information about the breakpoint that is hit. After that I can manually resume execution by pressing F5 or giving the go command.
The problem:
Some functions of the dll have to return very quickly (immediately) else the component crashes. In that case the breakpoint causes the component to crash. I can remove the breakpoint in question but then there would be no log of it being hit.
I looked around and found that I can run a command whenever a breakpoint is hit. bm module_name!func_name ".printf \"func_name\n\";gc" But this is not feasible for every exported function. The dll has about a few 100 exported functions.
What can I do to log (on the screen itself) every exported function that is hit (even the breakpoint number would do if nothing else can be done). Is there a variable name I can use in the printf command that can print the function name (or the breakpoint number if not the function name)?
Figured it out. Thanks to EdChum.
The command: bm *module_name!* ".frame;gc"

How to debug matlab code without gui

I have recently started using MATLAB without GUI by starting matlab with -nodesktop option and it is considerably faster.
However presently I have no way to debug a .m script in non gui mode. I have to open the default matlab editor every time I have to debug.Has anyone figured out a way to do it?
Thanks in advance
I am using Ubuntu Linux, in case that helps.
To set breakpoints with the command line, dbstop is the tool (plus dbclear to clear breakpoints and dbstatus to list them).
There are presently 17 different forms to dbstop, which allow you to specify various combinations of:
The M-file in which to stop
Line number
Sub-function
Conditional to an arbitrary expression. For example,
dbstop in myFun.m at 224 if ~exist('x','var')
At any run-time error (dbstop if error)
At a specific error (e.g dbstop if error myFun.m:barErrorId)
At any warning (dbstop if warning) or specific warning
If NaN or Inf are encountered (dbstop if naninf)
See the documentation for dbstop for details and good examples.
Also get used to dbcont (or F5), dbstep (or F10), dbquit (Shift+F5), dbstep (also dbstep in, dbstep out), dbstack (to see where you are and how you got there). The keyboard shortcuts may be different outside of Windows.
Far less used, but still very useful are dbup and dbdown, which allow you to switch workspace context (memory stacks).
See the summary of functions and a list of examples and how-to pages in the MathWorks page on Debugging.
Related to the "db" functions is checkcode, which will check your code for possible problems before you even run it. This is a nice substitute for the red squiggly underlines that you would get in the MATLAB Editor.
Once you get a hang of dbstop and it's syntax, you won't often need to insert a keyboard into your code, but it's always an option.
Try placing the keyboard command in your code to insert a breakpoint. When the keyboard command is reached, MATLAB will drop into an interactive prompt that you can use to inspect variables. For example:
x = rand(10,10);
y = rand(10,5);
z = x * y;
keyboard; % you can interactively inspect x, y, z here
z = sort(z);
To leave keyboard mode, you can type dbquit to exit the program, or return to continue executing the program.
Another trick is to turn on dbstop if error which will automatically drop you into an interactive prompt whenever your code crashes.
You can use MATLAB -Dgdb if that helps. This sets gdb as the debugger. You will need to be familiar with gdb of course.
Once you do that, use the standard gdb commands to debug it.
EDIT
My mistake. Above won't work for M-Files. (Not having MATLAB to try things out is a pain :)
MATLAB has a pretty good set of debugging commands you can use from the commandline. If you insert keyboard commands in your MATLAB code, you can then use the commands.
You can use MATLAB's editor debug button to debug within MATLAB environment

undefined variable in MATLAB

I am newbie to MATLAB .I have written a code to upsample a data.when executed always shrows the particular error(below)
??? Input argument "n" is undefined.
Error in ==> upsamp at 7
mm=min(n)
but when i just write the foll. output [n1,y]=upsamp([1,2,3,4,5,6],-1:4,3) command window ,its shows me the correct upsampled data with its figure.
then why the error is popping up? Or i just click on run button,and error is shown in command window.
Please help me out to debug that error:
My code is
function[n1,y]=upsamp(n,x,I)
mm=min(n)
mx=max(n)
n1=mm*I:(mx*I+I-1)
x1=x'
x1=[x1,zeros(length(x),I-1)]
x1=x1'
y=(x1(:))'
subplot(2,1,1)
stem(n,x)
title('original sequence ')
xlabel('Range')
ylabel('sequence')
subplot(2,1,2)
stem(n1,y)
title(' unsampling')
xlabel('Range')
ylabel('sequence')
end
As others have noted, if you want to run a function that takes input arguments, you have to call it manually from the command prompt with any required arguments.
Otherwise, if you like to use the Run button (F5) from the editor, consider creating a run configuration (they can be used in smart ways)
The "run" button is only for scripts (i.e. just a plain list of statements without "function" at the top). This is a function, so it should only get called from the matlab command line like you described.
The run button calls your function with no arguments.
Since arguments to your function are non-optional, you get an error.
Either call your function from the interactive Command Window, or write a short script that provides appropriate arguments, and use the Run button with that script. You can still single-step into your function.