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

采纳的回答

Torsten
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')

更多回答(2 个)

David Hill
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

Cris LaPierre
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

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by