필터 지우기
필터 지우기

How to Call a Function Within a Script?

조회 수: 3 (최근 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 CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

태그

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by