solve an ode with three methods in the same script
2 次查看(过去 30 天)
显示 更早的评论
Hi all,
I have a differential equation and I want to solve it using Runge Kuta, Midpoint method and euler.
So far I have created a function which includes the differential equation, called differential.m
I have created three script which correspond to each method. Those scripts call the differential function.
Names of the scripts are:
euler_method.m
runge_kuta.m
midpoint_method.m
I want to create a function which includes all those scripts and in the work space the results from each method appear.
SO far I wrote this
function mainfunction=mainfunction(t,x)
runge_kuta
euler_method
Midpoint_method
end
But in the workspace nothing appears and in the command window only the results from the midpoint method appear
0 个评论
回答(1 个)
Jan
2021-12-19
编辑:Jan
2021-12-19
Each function has its own workspace. The results of the called scripts are stored in the workspace of the function mainfunctionm but not in the base workspace, which is active in the command window.
Your code creates an error message, if it is called with an output:
function mainfunction=mainfunction(t,x)
...
end
Inside the function, the variabke "mainfunction" is not created, so it cannot be replied.
A solution is to convert the code for the integrations from scripts to functions:
function mainfunction(fcn, t, x0)
x_runge = runge_kutta(fcn, t, x0);
x_euler = euler_method(fcn, t, x0);
x_mid = Midpoint_method(fcn, t, x0);
% Now add some code here for plotting the results
end
Call this function as:
mainfunction(@differential, t, x0)
In the integrator functions replace differential() by fcn().
2 个评论
Jan
2021-12-19
"mainfunction - Not enough input arguments" - how did you start the function? With the suggested:
mainfunction(@differential, t, x0)
?
What are the inputs t and x? The time steps and the initial value? Then this is a Runge-Kutta function for the integration based on your script:
function x = runge_kutta(fcn, t, x0)
h = t(2) - t(1);
x = zeros(1, length(t));
x(1) = x0;
for i = 1:numel(t) - 1
k_1 = fcn(t(i), x(i));
k_2 = fcn(t(i) + 0.5 * h, x(i) + 0.5 * h * k_1);
k_3 = fcn(t(i) + 0.5 * h, x(i) + 0.5 * h * k_2));
k_4 = fcn(t(i) + h, x(i) + k_3 * h));
x(i+1) = x(i) + (h/6) * (k_1 + 2 * k_2 + 2 * k_3 + k_4);
end
end
Now the function is general and you can use it for all functions, time points and initial values. Convert the other scripts accordingly.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!