How to create a function that lets me choose the output (euler,Rk2 or Rk4)?

1 回表示 (過去 30 日間)
Danny Helwegen
Danny Helwegen 2018 年 12 月 22 日
編集済み: Danny Helwegen 2018 年 12 月 23 日
Hi guys, I have made an Euler solution, an RK2 and an RK4 solution for the same differential equation and now i want to put these all in one function so that i can choose from the command line which solution i want. I have tried several things, but I can't figure it out. Can anyone help me?
These are the codes for Euler, RK2 and RK4:
% Euler
function x = EULER(k,M,h,D) % Euler's method
...
return
% Runge Kutta 2
function x = rk2(k,M,N,D) % midpoint rule
..
return
% Runge Kutta 4
function x = rk4(k,M,N,D)
...
return

採用された回答

Cris LaPierre
Cris LaPierre 2018 年 12 月 22 日
All your functions have 4 inputs and one output, so that works out nicely. I would probably create a function declaration with a 5th input for indicating the method to use. For simplicity, I'll keep the other inputs the same. Use a switch statement on method and either call the appropriate function or copy the code for that function into the case. For conciseness, this calls the existing functions.
function x = mySolver(k,M,h,D,method)
switch lower(method)
case 'euler'
x = EULER(k,M,h,D); % Euler's method
end
case 'rk2'
x = rk2(k,M,h,D) % Runge Kutta 2
end
case 'rk4'
x = rk2(k,M,h,D) % Runge Kutta 2
end
end
It would then be called doing something like
x = mySolver(k,M,h,D,'euler')

その他の回答 (2 件)

madhan ravi
madhan ravi 2018 年 12 月 22 日

TADA
TADA 2018 年 12 月 22 日
Easiest Solution Would Be:
function x = solveDiffEq(k, M, step, D, method)
if nargin < 5; method = 'euler'; end
switch lower(method)
case 'euler'
x = EULER(k, M, step, D);
case 'rk2'
x = rk2(k, M, step, D);
case 'rk4'
x = rk4(k, M, step, D);
end
end
Now EULER IS The Default Method For solving, And If Specified Uses The Specified Method.

Community Treasure Hunt

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

Start Hunting!

Translated by