Compute x and y by integrating the ODE system using Huen's method.

8 次查看(过去 30 天)
trying to code a function - see below - any help would be appreciated - trying to compute x and y by integrarting the ODE using Huens method but can use ODE solvers.
function [x,y] = odeHuen (f,x0,h,nSteps,y0)
% Initialize the output solution arrays.
m = length(y0);
x = zeros(1,nSteps+1);
y = zeros(m,nSteps+1);
x(1) = x0;
y(:,1) = y0;
here need code to Compute x and y by integrating the ODE system using Huen's method.
here is the call to action function:
f = @(x,y) [y(2); -y(1)]; % ODE function, note this trial code should give cos and sin plots
x0 = 0; h = 0.1; nSteps = 100; y0 = [1; 0]; % Initial condition and solver parameters
[x,y] = odeHuen(f,x0,h,nSteps,y0);
plot(x,y)
legend({'$\mathbf{y}_1$','$\mathbf{y}_2$'},'Interpreter','latex','FontSize',16)

回答(1 个)

darova
darova 2021-4-2
You should use for loop
function [x,y] = odeHuen (f,x0,h,nSteps,y0)
% Initialize the output solution arrays.
m = length(y0);
x = x0:h:nSteps*h;
y = zeros(2,nSteps+1);
x(1) = x0;
y(1) = y0;
for i = 1:nSteps-1
y(:,i+1) = y(:,i) + h*f(x(i),y(:,i));
y(:,i+1) = y(:,i) + h/2*(f(x(i),y(:,i) + f(x(i),y(:,i+1));
end
  1 个评论
Louis Graham
Louis Graham 2022-3-24
This returns an error message that says
File: solution.m Line: 12 Column: 39
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
Do you know why?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Ordinary Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by