Error Message: Improved Euler Step method code

3 views (last 30 days)
Hi everyone! I am working on a code that solves an equation using the improved euler method. I have all my variables in place, but whenever I try to run the code I get multiple error messages which don't tell me explicity what the error is. I'm not quite sure what I could be doing wrong, but I can put my code here if anyone has any suggestions. The error message is occurs at the dV2=... line in the rhs function, the y_low=... line in the improved_euler_step function, and in the first line after the while loop.
The first function is the function I am trying to run. I uses function handles to call the other two functions. The second is the improved euler step function. The third is a function that solves the rhs of the equation provided to be used for the improved euler method. I am trying to run with the given parameters defined in the param statement and over a timespan of 0-100 (which is input as tspan). The initial conditions for y are y(0)=0, y'(0)=0. Thank you all so much for your help!!
[t_out, y_out] = ode(@rhs, @improved_euler_step, [0 100], [0;0], 0.5);
param=[0.5 0.1];
y=[V;dV];
yp=[dV;dV2];
function [t_out, y_out] = ode(rhs, method, tspan, y_init, h)
t=tspan(1)
t_out=[t];
y=y_init;
y_out=[y_init(1), y_init(2)];
while t<tspan(2)
[t_2,y_low,y_high]= method(rhs,t,y,h);
y=y_high;
t_out=[t_out;t_2];
y_out=[y_out; y_high];
end
end
function [t_2, y_low, y_high] = improved_euler_step(rhs, t_2, y, h)
% calculate the next time by increasing the current time, t_in by one time step h
t_2 = t_2 + h;
% calculate an approximation of y at t_out using Euler
y_low = y + h*rhs(t_2,y);
% calculate an approximation of y at t_out using improved Euler.
y_high = y + h*(rhs(t_2,y) + rhs(t_2, y_low))/2;
end
function yp = rhs(t, y, param)
t=t;
V=y(1);
dV=y(2);
dV2= -dV-param(1)*V +cos(param(2)*t);
yp= [dV;dV2]
end

Accepted Answer

Walter Roberson
Walter Roberson on 25 Feb 2021
rhs expects 3 parameters but you only pass it two
  1 Comment
Catherine Zdunek
Catherine Zdunek on 25 Feb 2021
Hi! Thank you so much for you're response; that small mistake fixed the rest of my code! Thank you a bunch!!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!