Why do I receive error stating that function needs to appear at the end of the file? MATLAB Differential Equations Help
8 次查看(过去 30 天)
显示 更早的评论
May someone help me figure out why I keep getting the error at the end of this message?
global alpha
global beta
% Y = [x(t) y(t)], Y(1) = x(t), Y(2) = y(t)
function [dx_dt dy_dt] = odefun(t, Y)
x = Y(1); y = Y(2);
global alpha
global beta
dx_dt = beta * (1 - x - y) * x - alpha * x;
dy_dt = alpha * x;
end
alpha = 0.1;
beta = 0.1;
for x0 = [0:0.05:0.5]
alpha = 0.1
beta = 0.1
fig = figure;
[t_array, Y_array] = ode45(odefun, [0:200], [x0 0]);
plot(t_array, Y_array)
end
alpha = 0.05;
beta = 0.2;
for x0 = [0:0.05:0.5]
fig = figure;
[t_array, Y_array] = ode45(@odefun, [0:200], [x0 0]);
plot(t_array, Y_array)
end
Error: File: projectF.m Line: 11 Column: 1
Function definitions in a script must appear at the end of the file.
Move all statements after the "odefun" function definition to before the first local function
definition.
0 个评论
回答(1 个)
Walter Roberson
2023-11-30
It is just a Fact Of Life with MATLAB. You have some non-function statements, then you define a function, then you end the function, then you have more non-function statements. MATLAB considers your script (the original non-function statements) to have ended as soon as the first function definition appeared, and doesn't know what to do with the non-function statements after the function definition. Just move the function definition to the end.
global alpha
global beta
% Y = [x(t) y(t)], Y(1) = x(t), Y(2) = y(t)
alpha = 0.1;
beta = 0.1;
for x0 = [0:0.05:0.5]
alpha = 0.1
beta = 0.1
fig = figure;
[t_array, Y_array] = ode45(odefun, [0:200], [x0 0]);
plot(t_array, Y_array)
end
alpha = 0.05;
beta = 0.2;
for x0 = [0:0.05:0.5]
fig = figure;
[t_array, Y_array] = ode45(@odefun, [0:200], [x0 0]);
plot(t_array, Y_array)
end
function [dx_dt dy_dt] = odefun(t, Y)
x = Y(1); y = Y(2);
global alpha
global beta
dx_dt = beta * (1 - x - y) * x - alpha * x;
dy_dt = alpha * x;
end
3 个评论
Walter Roberson
2023-11-30
You cannot return multiple derivatives on the left side of an ode function. You need to return a column vector as the single output of the ode function. (There might potentially be other outputs as well, depending on options you have configured.)
global alpha
global beta
% Y = [x(t) y(t)], Y(1) = x(t), Y(2) = y(t)
alpha = 0.1;
beta = 0.1;
for x0 = [0:0.05:0.5]
alpha = 0.1
beta = 0.1
fig = figure;
[t_array, Y_array] = ode45(@odefun, [0:200], [x0 0]);
plot(t_array, Y_array)
end
alpha = 0.05;
beta = 0.2;
for x0 = [0:0.05:0.5]
fig = figure;
[t_array, Y_array] = ode45(@odefun, [0:200], [x0 0]);
plot(t_array, Y_array)
end
function [dxdy_dt] = odefun(t, Y)
x = Y(1); y = Y(2);
global alpha
global beta
dx_dt = beta * (1 - x - y) * x - alpha * x;
dy_dt = alpha * x;
dxdy_dt(1,1) = dx_dt;
dxdy_dt(2,1) = dy_dt;
end
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!