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

조회 수: 7 (최근 30일)
Pierre A
Pierre A 2021년 4월 2일
댓글: Louis Graham 2022년 3월 24일
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