undefined variable in MATLAB - 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.

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.

Alternatives to `clear(function_name)` to remove function from RAM?

As stated in MATLAB's FAQ,
1.3.3.1. Why, when I edit a function file in MATLAB, is the change not seen by MATLAB until everything is cleared or MATLAB is restarted?
When you write an M-file in MATLAB, you can either write a script or a
function. The difference is that a script is read from the disk and
parsed line by line each time it is called. A function is loaded into
RAM for execution. Because it is loaded into RAM, when you edit a
function, that change is not loaded into RAM until a call to the new
function is made.
To get MATLAB to recognize your edited function, type
clear functions to clear all functions, or
clear <function name> to clear just your function out of RAM.
This is a major pain when I'm developing a function & editing it repeatedly (I use an external editor most of the time). I was thinking of putting in a final line, at least during debug, like
clear(myfunc)
but I'm concerned about unwanted side effects. Does anyone know if there are any?
Further, I'd rather have a way to configure MATLAB so it doesn't automatically store called functions in RAM once the top-level function (i.e. the one called from the console) terminates. Is that even possible?
EDIT: I should mention that MATLAB's behavior is inconsistent. Sometimes my edits take effect once I save the m-file, other times they don't even if I'm editing with the MATLAB IDE editor window.
In all honesty MATLAB has a very powerful editor so you really should
be using it. It will make you life easier. (just an opinion)
Unless you are running the code by stepping through it no change to code will be run until the code is re-run (preferably with a cleared workspace).
clear(myfunc) will clear the variables created by that function in upto that point. You can add at the end of any function or script clear variableA variableB for all variables you want cleared at the end. This will give you control to only clear what you want. Once variables are cleared the only effect will be that if those variables are called again later in the code an error will occur since they no longer exist.
If your simply testing that particular function and want to save time by not calling inputs each time and want to clear the workspace and command window at the same time. You can add the following code just beneath the function definition.
If you leave the following code and call the function from another function or script, the code will be ignored as long as the inputs are available to it externally. Anything you add to the if statement will only occur when you call the function with no inputs doc nargin. You could add it to the top level function and you would simply press the run button or f5 without having to type in the command window to run the code.
function [ output1, output2 ] = blah( input1, input2 )
if nargin == 0
clc
clear all
%above two lines will clear the workspace and command window when you run
%the function
%define function inputs
%(optionally add the following to behave as if you inserted a breakpoint
%in the location just before the error occurred (great for debugging)
db stop if error
end
*you can also add a short-cut to snippets of code up in the top right of the MATLAB interface to clear the workspace etc when they are clicked.
Hackish* idea for this:
I'd rather have a way to configure MATLAB so it doesn't automatically store called functions in RAM once the top-level function (i.e. the one called from the console) terminates. Is that even possible?
* This is the sort of thing I might use, while advising others on why it is a bad idea, also probably uses undocumented (thus unreliable) things.
Specifically if your using an external editor I guess your going to have to click on the command window to run the function...
commandWindowHandle = ...
handle(com.mathworks.mde.desk.MLDesktop.getInstance.getClient('Command Window'...
.getComponent(0).getComponent(0).getComponent(0),'CallbackProperties');
commandWindowHandle.MouseClickedCallback = 'clear functions'
It doesn't clear the function definitions on exiting a function rather on clicking on the command window
note: the callback will not fire if a function is currently running
For a potentially more reliable but more wasteful version:
commandWindowHandle.KeyPressedCallback= 'clear functions'
will help* ensure definitions are clear, but is wasteful as every keystroke will run 'clear functions'... although after one keystroke this will be quicker as there will be no functions in memory!
* No guarantee I know there are ways in which this could fail... having at least 1 keystroke in the command window after the previous function call has finished would be advisable!
To disable these set the callback to empty string ''
commandWindowHandle.MouseClickedCallback = ''
commandWindowHandle.KeyPressedCallback= ''

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

Difference between "step" and "step in" in the MATLAB debugger

What is the difference between "Step" and "Step in" in the MATLAB debugger? As far as I have tested them in some debugging so far they gave me the same steps and results.
When you use step in on a function call, you will enter said function. step is used to move to the next line. When you use them on lines without function calls, they are equivalent.
The command dbstep (or the debugger tool "Step") executes the next line of code. It does not stop within that function, even if that function is implemented in MATLAB code and contains breakpoints.
The command dbstep in (or the debugger tool "Step In") also executes the next line of code, but if that line is a call to a function implemented in MATLAB code (i.e. not a built-in), it will enter that function and stop at the next line of code within the function.
If the next line is not a call to a function implemented in MATLAB code, dbstep and dbstep in are equivalent.
See the Matlab doc: dbstep
Basically, Step executes the next line, even if there is a call to complex function/other script. Step In jumps in the code on the called function if possible, else executes the entire line.

Difference between script and matlab command window

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.