Runge-Kutta function

8 ビュー (過去 30 日間)
john smith
john smith 2019 年 5 月 29 日
回答済み: Meysam Mahooti 2021 年 7 月 28 日
derive a Matlab function that receive a Second-order differential equation and step size and initial value from user and solve it with 4th order Runge-Kutta or 2nd order Runge-Kutta which is choosen by user.
  2 件のコメント
James Tursa
James Tursa 2019 年 5 月 29 日
What have you done so far? What specific problems are you having with your code?
john smith
john smith 2019 年 5 月 29 日
i dont know how to receive the equation and the way to solve it (4th order Runge-Kutta or 2nd order Runge-Kutta)?

サインインしてコメントする。

回答 (2 件)

James Tursa
James Tursa 2019 年 5 月 29 日
編集済み: James Tursa 2019 年 5 月 29 日
Here is some code to get you started. It receives a string from the user for a derivative function of x and t and turns it into a function handle that can be used in an RK scheme.
s = input('Input an expression for the derivative of x (it can use t also): ','s');
dx = str2func(['@(t,x)' s]);
Now you have a function handle that calculates the derivative of x. You call it with the current time t and state x: dx(t,x)
E.g., running this code:
Input an expression for the derivative of x (it can use t also): cos(x) + t*x^2
>> dx
dx =
function_handle with value:
@(t,x)cos(x)+t*x^2
However, if your derivative function involves variables from the workspace, then you will need to use eval( ) instead because str2func( ) can't see those local variables when it creates the function handle:
dx = eval(['@(t,x)' s]);
E.g.,
>> a = 5;
>> s = input('Input an expression for the derivative of x (it can use t also): ','s');
Input an expression for the derivative of x (it can use t also): a*cos(x)+t*x^2
>> dx = str2func(['@(t,x)' s]);
>> dx(2,3)
Undefined function or variable 'a'. <-- str2func didn't work
Error in @(t,x)a*cos(x)+t*x^2
>> dx = eval(['@(t,x)' s]);
>> dx(2,3)
ans =
13.0500 <-- eval did work
For the RK4 and RK2 schemes, what has your instructor given you? Surely there must be algorithms for this that were discussed in class.

Meysam Mahooti
Meysam Mahooti 2021 年 7 月 28 日
https://www.mathworks.com/matlabcentral/fileexchange/55430-runge-kutta-4th-order?s_tid=srchtitle

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by