Please help! "Error: Function definitions are not permitted in this context. "

481 views (last 30 days)
Hello! I'm extremely new to Matlab, and I'm working on a homework problem, and I keep coming up with an error... I've written my functions, and defined some variables to be plugged into them. I can't even call my functions, because I get the error for writing them.
This all has to be in one m-file so I cannot save the functions in different ones... I'm not sure what to do :(
function [x,y,vx,vy] = trajectory(t,v0,th0,h0,g)
x = v0 .* cos(th0) .* t;
y = h0 + (v0 .* sin(th0) .* t) - ((1./2) .* g .* (t.^2));
vx = v0 .* cos(th0);
vy = (v0 .* sin(th0)) - (g .* t);
function y = height(t,v0,th0,h0,g)
[x,y,vx,vy] = trajectory(t,v0,th0,h0,g);
%(b)
v0 = 20;
th0 = 45;
h0 = 5;
g = 9.81;
t = linspace(1,4,400);
y = height(t,v0,th0,h0,g)
  3 Comments
Image Analyst
Image Analyst on 25 Sep 2016
Essentially, the code simplifies down to this:
function a = trajectory
a=10
function height
b = trajectory
c = height
There is nothing wrong with having that all in the same m-file. You can run it and won't get the error. Basically it runs trajectory, which never calls height at all. If it did, then since height calls trajectory, you could get an infinite loop because it would never stop.
What they probably did (but did not show) was to define t,v0,th0,h0,g in the same m-file, and this turned the two-function file (which is allowed) into a script+(2 functions) file which is not allowed. You can't start out an m-file with a script (like defining input arguments) and then follow up with function definitions. You can have a script only, or multiple functions, but not both in the same m-file.

Sign in to comment.

Accepted Answer

Fangjun Jiang
Fangjun Jiang on 16 Oct 2011
Edited: MathWorks Support Team on 8 Nov 2018
In MATLAB, there are two types of code files, scripts and functions. If the first executable line of your code file is a function definition like you have in the code above, then your file is a function.
If there is other MATLAB code such as variable declarations above the first function definition, then your file is a script. It sounds like you might have additional code above the code for the two functions you gave, making the file a script.
In MATLAB versions R2016a and before, you cannot have function definitions inside a script. That is what the error message is saying. To fix the problem, save each function definition in separate files, and either create a script with the additional code or simply run the additional code in the command window before calling your functions.
In MATLAB version R2016b and after, you can have function definitions in a script, and you would not see the "Error: Function definitions are not permitted in this context" error in your case. For more information about functions in scripts, see:
For more information about the difference between scripts and functions, see:
  12 Comments
chorare chorare
chorare chorare on 18 Sep 2021
hello me to I also have the same problem and I know what to do
function y = pvMeasurementFcn(x,varargin)
% Extract data from inputs
Ts = varargin{1};
Is = varargin{2};
Rs = varargin{3};
Rp = varargin{4};
vt = varargin{5};
n = varargin{6};
Voc = varargin{7};
Iph = varargin{8};
% Output equation
y = [...
Iph-Is*exp((Voc+x(2)*Rs)/(n*vt)-1)-(Voc+x(2)*Rs/Rp); ...
Voc];
end
>> pvMeasurementFcn
Index exceeds matrix dimensions.
Error in pvMeasurementFcn (line 4)
Ts = varargin{1};
Walter Roberson
Walter Roberson on 18 Sep 2021
That function needs to be passed a minimum of 9 parameters. The first one is x, then Ts, Is, Rs, and through Rp, vt, n, Voc, and Iph .
You attempted to run the function without passing any parameters at all. The function has no idea where to get the values for Ts, Is, Rs and so on from.
You cannot just press the green Run button to invoke that function. You need to go down to the command window and invoke it passing in values, like
y = pVMeasurements(x20210903, Ts7, Is7, Rs7, Rp5, vt4, 17, Voc_holiday, pale_ale)
but using the actual variable names for your data instead of the names I gave here.

Sign in to comment.

More Answers (7)

Walter Roberson
Walter Roberson on 16 Oct 2011
In addition to what Fangjun wrote:
When you are not already executing within a given file, MATLAB can only find the very first function in that file, and that first function name must be the same name as the file.
Therefore, the order of functions in the file should be that the very first one is the "driver" function (the one that sets up everything and calls the other functions to do the work), and the functions that do the internal work should be after that in the file.
If you look at the function order you have coded above, you have coded the internal routine first, and then coded a routine that calls that internal routine. You would, however, not be able to activate that second routine from the MATLAB command line.
So... what you need to do is take the line that start at %(b) through to the end of the file, and move those lines to the beginning of the file, and then you have to insert a "function" line at the very top, naming it appropriately for your assignment conditions. I can see from the code that those lines set things up and then call the internal routines, so those lines should be in the first function.
  1 Comment
marah
marah on 16 Dec 2022
Error using struct2handle
Error while evaluating uicontrol CreateFcn
function varargout = lagrange(varargin)
|
Error: Function definitions are not permitted in this context.
function varargout = lagrange(varargin)
|
Error: Function definitions are not permitted in this context.

Sign in to comment.


Kamil Kasic
Kamil Kasic on 28 Jan 2014
Edited: Walter Roberson on 28 Jan 2014
What is wrong here?
basic example from Matlab help:
function y = average(x)
if ~isvector(x)
error('Input must be a vector')
end
y = sum(x)/length(x);
end
function y = average(x)
|
Error: Function definitions are not permitted in this context.
  4 Comments
ankar saha
ankar saha on 27 Aug 2022
what is wrong here
clc; close all; clear all;
input_data = zeros(1,10);
y_cofficient = [1 -1 -1];
x_cofficient = [0 0];
initial_condition = [0 1];
yn_function_generated = filter(x_cofficient,y_cofficient,input_data);
yn = myFilter(x_cofficient, y_cofficient, input_data, initial_condition);
subplot(4,1,1)
% plot(input_data);
stem(input_data);
title('Input data');
grid on;
subplot(4,1,[2,3]);
% plot(yy, LineWidth=1);
stem(yn);
title('Custom calculated');
grid on;
subplot(4,1,4);
% plot(y, LineWidth=1);
stem(yn_function_generated);
title('Function generated');
grid on;
% My Function
function [y] = myFilter(xCoff, yCoff, input_data, initial_condition)
xCoff_len = length(xCoff);
yCoff_len = length(yCoff);
xCoff = [xCoff, zeros(1, length(input_data) - xCoff_len)];
yCoff = [yCoff, zeros(1, length(input_data) - yCoff_len)];
output_size = length(xCoff);
y = zeros(1, max(output_size, length(initial_condition)));
for i = 1 : length(initial_condition)
y(i) = initial_condition(i);
end
for n = length(initial_condition)+1 : length(y)
y_sum = 0;
x_sum = 0;
for j = 2 : n
y_sum = y_sum + (yCoff(j) * y(n - j + 1));
end
for j = 1 : n
x_sum = x_sum + (xCoff(j) * input_data(n - j + 1));
end
y(n) = (x_sum - y_sum)/yCoff(1);
end
end

Sign in to comment.


Gedion Teklewolde
Gedion Teklewolde on 26 Mar 2014
Edited: Gedion Teklewolde on 26 Mar 2014
Even when it is saved in appropriate name file.m it still fails.
clc
clear
clc
%
% Newton-Raphson method
%
function [x0,err] = newraph(x0)
maxit = 100;
tol = 1.0e-6;
err = 100.0;
icount = 0;
xold =x0;
while (err > tol & icount <= maxit)
icount = icount + 1;
f = funkeval(xold);
df = dfunkeval(xold);
xnew = xold - f/df;
if (icount > 1)
err = abs((xnew - xold)/xnew);
end
fprintf(1,'icount = %i xold = %e f = %e df = %e xnew = %e err = %e \n',icount, xold, f, df, xnew, err);
xold = xnew;
end
%
x0 = xnew;
if (icount >= maxit)
% you ran out of iterations
fprintf(1,'Sorry. You did not converge in %i iterations.\n',maxit);
fprintf(1,'The final value of x was %e \n', x0);
end
function f = funkeval(x)
f = x + log(x);
function df = dfunkeval(x)
df = 1 + 1/x;
  2 Comments
Walter Roberson
Walter Roberson on 10 Jan 2016
It is not clear what was stored in which file. The 'clc' at the top of the code is not the word 'function' or 'classdef' so whatever code is in the same file as the 'clc' is part of a "script" rather than a function file. Function files must start with "function", and functions can also be defined in "classdef" files, but functions cannot be defined in scripts.

Sign in to comment.


Gireesha Obulaporam
Gireesha Obulaporam on 28 Jan 2017
I wold like to implement a Genetic Algorithm in MATLAB. So, first I tried to execute the fitness value. I entered the function name called myFitness() which is as shown below:
function y = myFitness(x)
It displays me the "Error: Function definitions are not permitted in this context".
Please suggest me how to resolve it.
  1 Comment
Walter Roberson
Walter Roberson on 28 Jan 2017
You can never use "function" at the command line.
If you are using R2016a or earlier then functions can only be defined in a file that starts with function or classdef. In R2016b you can also put functions in a script.

Sign in to comment.


Valeria Martinuzzi
Valeria Martinuzzi on 5 Jun 2017
Edited: Walter Roberson on 5 Jun 2017
This function file is giving me an error even though it seems right. It is telling me that "Function definitions are not permited on this context" This is the file:
function [s,flag] = setupSerial(s)
%Initialize the serial port communication between Arduino and MATLAB
%The input value is the COMPORT should be changed as per requirement
%We ensure that the arduino is also communication with MATLAB at this
%time. A predefined code on the Arduino acknowledges this.
%If setup is complete then the value of setup is returned as 1 else 0
flag = 1;
s= serial('COM3');
set(s,'DataBits', 8);
set(s,'StopBits', 1);
set(s,'BaudRate', 9600);
set(s,'Parity','none');
fopen(s);
a='b';
while (a~='a')
a=fread(s,1,'uchar');
end
if (a=='a')
disp('serial read');
end
fprintf(s,'%c','a');
mbox = msgbox('Serial Communication setup.'); uiwait(mbox);
fscanf(s,'%u');
end
Help please?

Nkwentie Musi
Nkwentie Musi on 11 Jul 2017
after defining my function like this Function(Zg,Zt,Zc,Yg,ZT,YT)= LineParameters(Mu,Eo,Rsu,Geom,Ncon,Ns,w) i have this error when executing the program "??? Error: File: testfinal.m Line: 41 Column: 1 Function definitions are not permitted in this context." what was i suppose to do
  3 Comments
marah
marah on 16 Dec 2022
When I run the interface, I get this error
function varargout = lagrange(varargin)
|
Error: Function definitions are not permitted in this context.
function varargout = lagrange(varargin)
|
Error: Function definitions are not permitted in this context.
can you help me
Walter Roberson
Walter Roberson on 16 Dec 2022
marah
You are trying to define a function at the command line. You need to store the code in lagrange.m

Sign in to comment.


Han Wang
Han Wang on 10 Dec 2018
There is nothing wrong creating functions in .m files, but I think the mistake you are making is that you didn't put the functions at the END of you mfile. Matlab actually enforces that they have to be placed at the end of the file, in order to avoid confusions like the one you have shown in your example. I think apparently, Matlab thinks your codes following %(b) are part of the function "height", and thus it gets confused somehow.
Matlab is indeed sending you a wrong error message because it minsinterprets your whole code structure. You can try moving your main routine following %(b) to the beginning of the code. Also, it helps to attach "end" to each function you have defined.
I have encountered similar situations like yours, where I forgot to attach an "end" to a "for" loop in the main routine, and Matlab sends me the same error message as yours, apparently confused with the code structure.
  2 Comments
Walter Roberson
Walter Roberson on 10 Dec 2018
At the time the question was asked in 2011 functions could not be stored in script files .
Steven Lord
Steven Lord on 10 Dec 2018
Matlab actually enforces that they have to be placed at the end of the file, in order to avoid confusions like the one you have shown in your example.
That's not completely correct. There are three scenarios in which ending each function in a file with an end statement is required. See the "End Statements" section on this documentation page for the list of those scenarios.
You can have a function file in which none of the functions end with an end or a function file in which all of the functions end with an end. What's not allowed is for some but not all of the functions to end with an end.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!