Error function definitions are not permitted at the prompt or in scripts

Подскажите, почему при запуске .м файла в котором определена фукнция: function [ligh1,ligh2,ligh3,low1,low2,low3,Upr]=rele(ia_ref,ib_ref,ic_ref,ia_load,ib_load,ic_load,Upr)

_Сергей_

Пользователь
Сообщения: 6
Зарегистрирован: Сб сен 13, 2008 1:21 pm

Ошибка.

Подскажите, почему при запуске .м файла в котором определена фукнция:

function [ligh1,ligh2,ligh3,low1,low2,low3,Upr]=rele(ia_ref,ib_ref,ic_ref,ia_load,ib_load,ic_load,Upr)

матлаб пишет ошибку:

??? Error: File: rele.m Line: 2 Column: 1

Function definitions are not permitted at the prompt or in scripts.


Камиль

Пользователь
Сообщения: 44
Зарегистрирован: Пт янв 05, 2007 8:51 pm

Re: Ошибка.

Сообщение Камиль » Сб сен 27, 2008 3:09 pm

может я и тупость скажу, я в матлабе не очень.. По моему, сами функции запускать нельзя, их можно только вызывать из сценария. Если я прав (что навряд ли), то эту ошибку можно обойти, стерев первую строчку и входные данные сделав глобальными либо введя их в самом сценарии


_Сергей_

Пользователь
Сообщения: 6
Зарегистрирован: Сб сен 13, 2008 1:21 pm

Re: Ошибка.

Сообщение _Сергей_ » Сб сен 27, 2008 3:12 pm

Камиль писал(а):может я и тупость скажу, я в матлабе не очень.. По моему, сами функции запускать нельзя, их можно только вызывать из сценария. Если я прав (что навряд ли), то эту ошибку можно обойти, стерев первую строчку и входные данные сделав глобальными либо введя их в самом сценарии

Все переменные , как входные так и выходные уже определены в первой строчке как global.


Камиль

Пользователь
Сообщения: 44
Зарегистрирован: Пт янв 05, 2007 8:51 pm

Re: Ошибка.

Сообщение Камиль » Сб сен 27, 2008 3:14 pm

Но не трудно же в начале первой строки function…. поставить %. Если это не сработает, то приношу свои извинения за отнятое у Вас время


_Сергей_

Пользователь
Сообщения: 6
Зарегистрирован: Сб сен 13, 2008 1:21 pm

Re: Ошибка.

Сообщение _Сергей_ » Сб сен 27, 2008 3:22 pm

Камиль писал(а):Но не трудно же в начале первой строки function…. поставить %. Если это не сработает, то приношу свои извинения за отнятое у Вас время

Нет , это не работает )

Врятли закомментировав функцию она начнет работать )


Камиль

Пользователь
Сообщения: 44
Зарегистрирован: Пт янв 05, 2007 8:51 pm

Re: Ошибка.

Сообщение Камиль » Сб сен 27, 2008 3:25 pm

А так хотелось, что бы сработало)) Удачи


_Сергей_

Пользователь
Сообщения: 6
Зарегистрирован: Сб сен 13, 2008 1:21 pm

Сообщение _Сергей_ » Пн сен 29, 2008 6:24 pm

Неужели все так плохо?


vvamy

Эксперт
Сообщения: 654
Зарегистрирован: Ср сен 22, 2004 4:49 pm

Сообщение vvamy » Вт сен 30, 2008 11:45 am

Нельзя определять функцию в script-файлах! Функции можно определять (задавать) в теле других функций.

В Вашем случае можно сделать, например, так:

function y=Untitled

x=1;

y=add1(x); % вызов ф-ии add1

function y=add1(x) % определение ф-ии add1 в теле ф-ии Untitled

y=x+1;

См. также Help/MATLAB/Programming/Types of Functions/Subfunctions.

Виталий.


Agata

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);

v0 = 20;

th0 = 45;

h0 = 5;

g = 9.81;

t = linspace(1,4,400);

y = height(t,v0,th0,h0,g)

采纳的回答

Fangjun Jiang

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:


更多回答(7 个)

Walter Roberson

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.


Kamil Kasic

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.


Gedion Teklewolde

Even when it is saved in appropriate name file.m it still fails.

clc

clear

clc

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)

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;


Gireesha Obulaporam

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.


Valeria Martinuzzi

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)

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

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


Han Wang

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.

另请参阅

类别

Community Treasure Hunt

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

Start Hunting!

发生错误

由于页面发生更改,无法完成操作。请重新加载页面以查看其更新后的状态。

Translated by Microsoft

Skip to main content

Forum for Electronics

Forum for Electronics

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals… and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

  • Digital Design and Embedded Programming

  • Digital communication

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

MATLAB Error: Function definitions are not permitted at the prompt or in scripts.


  • Thread starter

    popat_panjaru


  • Start date

    Mar 17, 2007

Status
Not open for further replies.

  • #1

Full Member level 2

Joined
Mar 4, 2007
Messages
129
Helped
3
Reputation

6

Reaction score
0
Trophy points
1,296
Activity points

2,248


hi to all

i m new learner in matlab so at the time of learning when i m trying to run any ready MATLAB program i always get one error msg like this

function hh = dtmfdesign(fcent, L, fs)
|
Error: Function definitions are not permitted at the prompt or in scripts.

so can anybody tell me what is it?..and how can i solve it?..

plz help me out..

Popatlal Panjarawala

  • #2

Full Member level 5

Joined
Oct 22, 2005
Messages
295
Helped
27
Reputation

54

Reaction score
5
Trophy points
1,298
Location

South Africa

Activity points

3,462


Re: MATLAB Error

Hi,
In order to define the function you have to make a new .M file. In that way you can create the function and the call it from the command prompt.

  • #3

Full Member level 2

Joined
Mar 4, 2007
Messages
129
Helped
3
Reputation

6

Reaction score
0
Trophy points
1,296
Activity points

2,248


Re: MATLAB Error

which kind of new .m file i have to create?..i cant able to understand what u r saying?…can u give me one short and sweet example for it????????

  • #4

bee

Full Member level 2

Full Member level 2

Joined
Nov 29, 2003
Messages
135
Helped
7
Reputation

14

Reaction score
5
Trophy points
1,298
Activity points

883


Re: MATLAB Error

here u go…

1.funtion should be made in new m-file
2. u can make m-file by clicking the top left file ->New -> M File.
3. the format of first line (other than comments) should be
function [output1,output2] = file_name(input1,input2)
3. type » help function» in matlan cmd prompt to get more help.
4. MOST IMP::::: name of file should be same as name of funcution name
e.g function [output] = test (input1)
here the name of the file SHOULD BE test.m or it will never work.
5. U can have as many outputs and inputs u want in the fields named output1 and input1.
6. One u made the function u can execute it by wirtting the name of fucntion on the command prompt with inputs
e.g test(1)
where » 1 » is the input data…

enjoy

  • #5

Full Member level 5

Joined
Oct 22, 2005
Messages
295
Helped
27
Reputation

54

Reaction score
5
Trophy points
1,298
Location

South Africa

Activity points

3,462


Re: MATLAB Error

Also if the function you are defining needs a second cutom function if may be defined within the same .m file as the main function.

It should be noted though that the second function will not be accessable from withing matlab and only the first function will be able to use it. (see example)

function [o1,o2] = function1(in1,in2) %Main definition in .m file

function [avg] = average(input_vector) %Sub function only available to function1

Cheers
Slayer

Status
Not open for further replies.

Similar threads

  • Digital Design and Embedded Programming

  • Digital communication

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

Как Quantum7 отметил,, вы определили функцию в том же скрипте, что приведет к ошибке. Независимо от того, находится ли функция в другом файле или нет, то, что вы там написали, не является допустимой операцией с символьными переменными. Если вы просто закомментируете вторую строку и запустите ее, вы получите следующую ошибку:

??? Ошибка при использовании ==> sym.sym> checkindex на 2697

Индекс должен быть целым положительным числом или логическим.

что потому что i-1 равен нулю для первого цикла, и MATLAB начинает отсчет с 1. Если вы попробуете for i=2:3, то вы получите эту ошибку,

??? Ошибка при использовании ==> mupadmex

Ошибка в команде MuPAD: индекс превышает размер матрицы.

потому что символьная переменная — это просто 1x1 массив.

Судя по тому, что вы написали, у вас есть массив T1и T2 построен из T1 согласно соотношению: T2(i)=T1(i)+2*[T1(i-1)+T1(i+1)]. Я думаю, что лучший способ сделать то, что вы пытаетесь, — использовать анонимные функции.

Я немного изменю индексацию, чтобы учесть тот факт, что в первом и последнем элементах вы получите ошибку, потому что индекс будет превышать T1границы. Тем не менее ответ тот же.

dummyT1=[0;T1(:);0];
f=@(i)(dummyT1(i+1)+2*(dummyT1(i)+dummyT1(i+2)));
T2=f(1:3)

Если вы не хотите добавлять нули, а вместо этого сделайте их круговыми (т. Е. T1(0)=T1(3)), то вы можете использовать тот же код, легко изменив определение f.

Понравилась статья? Поделить с друзьями:
  • Error function definition not supported in this context create functions in code file
  • Error function crosstab unknown does not exist
  • Error function cannot execute on a qe slice because it accesses relation
  • Error func no 8 hifi image
  • Error func no 11 recovery image error no 2 load failed