How to Call a Function Within a Script?
2 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
Still learning Matlab. I am trying to solve replicate a script on MathWorks website. The function on MathWorks website is shown below:
function dydt = vdp1000(t,y)
%VDP1000 Evaluate the van der Pol ODEs for mu = 1000.
%
% See also ODE15S, ODE23S, ODE23T, ODE23TB.
% Jacek Kierzenka and Lawrence F. Shampine
% Copyright 1984-2014 The MathWorks, Inc.
dydt = [y(2); 1000*(1-y(1)^2)*y(2)-y(1)];
[t,y] = ode15s(@vdp1000,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
However, when I run, I get an error "not enough input parameters, error in dydt = [y(2); 1000*(1-y(1)^2)*y(2)-y(1)];
I am able to get it to work when I run this part below separately and remove it from the code above...meaning two separate m files.
[t,y] = ode15s(@vdp1000,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
Question is how do I get the code/function above to work without running the lines below separately? Thank you!
[t,y] = ode15s(@vdp1000,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
0 个评论
采纳的回答
Torsten
2022-11-21
You have two options:
Either define your derivatives in a function:
[t,y] = ode15s(@vdp1000,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
function dydt = vdp1000(t,y)
%VDP1000 Evaluate the van der Pol ODEs for mu = 1000.
%
% See also ODE15S, ODE23S, ODE23T, ODE23TB.
% Jacek Kierzenka and Lawrence F. Shampine
% Copyright 1984-2014 The MathWorks, Inc.
dydt = [y(2); 1000*(1-y(1)^2)*y(2)-y(1)];
end
or you define your derivatives by a function handle directly in the script:
vdp100 = @(t,y)[y(2); 1000*(1-y(1)^2)*y(2)-y(1)];
[t,y] = ode15s(vdp100,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
0 个评论
更多回答(2 个)
David Hill
2022-11-21
%execute function
dydt=vdp1000(t,y);%must assign t and y prior to executing the function
function dydt = vdp1000(t,y)
dydt = [y(2); 1000*(1-y(1)^2)*y(2)-y(1)];
[t,y] = ode15s(@vdp1000,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
end
0 个评论
Cris LaPierre
2022-11-21
Here is how you run the example you mention. Note that the last 2 lines of code in the example are how you call the function, and not part of the function.
[t,y] = ode15s(@vdp1000,[0 3000],[2 0]);
plot(t,y(:,1),'-o')
function dydt = vdp1000(t,y)
%VDP1000 Evaluate the van der Pol ODEs for mu = 1000.
%
% See also ODE15S, ODE23S, ODE23T, ODE23TB.
% Jacek Kierzenka and Lawrence F. Shampine
% Copyright 1984-2014 The MathWorks, Inc.
dydt = [y(2); 1000*(1-y(1)^2)*y(2)-y(1)];
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!