Error Function definitions are not permitted in this context - matlab

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.

Related

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.

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 start a Matlab file without a function being at the top?

Say I have a file StackOverflow that has the following function on line 1:
function [hello] = hai(choice)
end
I then go to the command window and type in StackOverflow and it will run the function. However, I would like to start a timer as soon as the program begins.
That said, I get this error when I try to do so;
Function definitions are not permitted in this context
How can I run this file without the function being at the top of the document?
From the documentation of creating functions in files:
The definition statement is the first executable line of any function.
Function definitions are not valid at the command line or within a
script.
In short, you can't have a line of code before the function definition. You have two choices: you can start the timer within the function, or you can start the timer at the command line immediately before calling the function.
If you go with the second option, I suggest using shift-enter after the command to start the timer, before calling your function, so both commands are executed one immediately after the other. Or, you can just use a semi-colon after starting the timer and add the second command on the same line. In either case, both will execute when you hit enter.

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.

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.