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

1 visualizzazione (ultimi 30 giorni)
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];

Risposta accettata

Image Analyst
Image Analyst il 30 Set 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 Commenti
Image Analyst
Image Analyst il 30 Set 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 il 30 Set 2014
Modificato: John D'Errico il 30 Set 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.

Accedi per commentare.

Più risposte (1)

sarvesh aundhkar
sarvesh aundhkar il 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];

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by