how can i solve y'=t/t^2+1 by programming a runge kutta 4'th order method ?

1 view (last 30 days)
i need a code

Accepted Answer

Matt Tearle
Matt Tearle on 18 Feb 2014
  1. As written, this can't be done, because there's a singularity at t = 0
  2. Assuming that you actually mean y' = t/(t^2 + 1)... why would you need RK4? The ODE can be solved by simple integration: y(t) = log(sqrt(t^2 + 1))
  3. If you really really want to do it numerically:
% Define ODE rate equation
ratefun = @(t,y) t/(t^2+1);
% Solve for t in [0,1] with initial condition y(0) = 0
[t,y] = ode45(ratefun,[0,1],0);
% View solution
plot(t,y,t,log(sqrt(t.^2+1)))
legend('RK45','exact','Location','NW')
But... ode45 is a variable-step RK45 integrator, not the classical fixed-step RK4 method. If you really want the fixed-step RK4 method for an equation with a simple analytic solution... well, then I have to assume that this is a homework problem.
If this is a homework problem, please do not just post a request for the solution. Show what you have done, and ask a specific question for guidance on a particular part of the problem.
  2 Comments
verica
verica on 19 Feb 2014
Error using rk4 (line 2) Not enough input arguments.
function q=rk4(x,t,h) u1=h*eval('t,x'); u2=h*eval('t+h/2,x+u1/2'); u3=h*eval('t+h/2,x+u2/2'); u4=h*eval('t+h,x+u3'); x1=x+(1/6)*(u1+2*u2+2*u3+u4); q=[x1];
Matt Tearle
Matt Tearle on 20 Feb 2014
This error message usually means the classic mistake of trying to run a function as a script (often by pushing the "Run" button on the toolstrip). This is equivalent to calling the function with no inputs. Instead, you have to call the function from the command line or another file with, in this case, three inputs specified:
y = rk4(0,0,0.1);
However, you're still going to have problems. First, eval evaluates a string as a command, so all you're achieving with the various eval calls is evaluating t + h/2 and so on. You can get the value of t + h/2 by just calculating t + h/2! The RK4 method needs a function to be evaluated with these inputs. In your case, the function would be f(t,x) = t/(t^2 + 1).
Finally, your code implements only a single step. RK4 iterates by taking multiple steps. In your case, to go from t = 0 to t = 1 with steps of h = 0.1, you need (1 - 0)/0.1 = 10 steps. A for loop will probably be helpful.

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!