How to Call a Function Within a Script?

4 ビュー (過去 30 日間)
Learning
Learning 2022 年 11 月 21 日
回答済み: Cris LaPierre 2022 年 11 月 21 日
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 Center および File ExchangeOrdinary Differential Equations についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by