how to correct ''Function definitions are not permitted in this context.''

1 Ansicht (letzte 30 Tage)
Function definitions are not permitted in this context.
a = 0.5;
B = 0.6;
k = 1;
[t, x] = ode45(@Ray, [0 30],[ 0 0.1], [], a, B, k);
plot(x(:,1), x(:,2), 'k-')
function d = Ray(t, y, a, B, k)
d=[y(2);-k*y(1)+a*y(2)-B*y(2^3];

Akzeptierte Antwort

Image Analyst
Image Analyst am 30 Sep. 2014
You can't have a script and a function inside the same m-file. You can have two functions and they don't need to be nested . For example if your m-file is called test.m, you could have test() and Ray() both inside test.m like this:
function test()
a = 0.5;
B = 0.6;
k = 1;
[t, x] = ode45(@Ray, [0 30],[ 0 0.1], [], a, B, k);
plot(x(:,1), x(:,2), 'k-')
function d = Ray(t, y, a, B, k)
d=[y(2);-k*y(1)+a*y(2)-B*y(2^3];
  3 Kommentare
Image Analyst
Image Analyst am 30 Sep. 2014
I believe they're not nested. Even if you put an end at the end of each one they're still not nested. Ray would not be nested inside test unless the end for test() occurred after Ray(), because in that case Ray would lie completely inside (nested) of test.
John D'Errico
John D'Errico am 30 Sep. 2014
Bearbeitet: John D'Errico am 30 Sep. 2014
Star - This is NOT a nested function. It is a sub-function, a different animal. A nested function can see the workspace of the parent function. A sub-function cannot, although it resides in the same file. There is a difference, and it is essentially controlled by proper placement of appropriate end statements as Image has stated.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

sarvesh aundhkar
sarvesh aundhkar am 22 Nov. 2017
function test() a = 0.5; B = 0.6; k = 1; [t, x] = ode45(@Ray, [0 30],[ 0 0.1], [], a, B, k); plot(x(:,1), x(:,2), 'k-') function d = Ray(t, y, a, B, k) d=[y(2);-k*y(1)+a*y(2)-B*y(2^3];

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by