Question

Problem # 1 P-1 Solve the following initial value problem using a4 order RK scheme: dy dx=tan(x), y(0)= 0.0 - Compare your re

use matlab only please
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Matlab code using RK4 for 1st order differential equation clear all close all Program for RK4 %function of 1st order diffrenttitle(x vs. y plot legend(RK4 solution, Exact solution,ode45 solution, location,best) tprint f ( Error in RK4 soluti

%%Matlab code using RK4 for 1st order differential equation
clear all
close all

%Program for RK4
%function of 1st order diffrential eqn
f=@(x,y) tan(x);
%step size
h=0.01*pi;
%all final time steps

    x(1)=0;y(1)=0; %initial conditions
    x_in=x(1);     %Initial x
    x_max=pi/4;    %Final x
    %Runge Kutta 4 iterations
    n=(x_max-x_in)/h;
    for i=1:n+1
     
        k0=h*f(x(i),y(i));
        k1=h*f(x(i)+(1/2)*h,y(i)+(1/2)*k0);
        k2=h*f(x(i)+(1/2)*h,y(i)+(1/2)*k1);
        k3=h*f(x(i)+h,y(i)+k2);
        x(i+1)=x_in+i*h;
        y(i+1)=double(y(i)+(1/6)*(k0+2*k1+2*k2+k3));
      
    end
    %printing the result
    fprintf('\tThe value of y at x=%2.2f for h= %2.2f is %f\n',x(end),h,double(y(end)))
  
%function for exact solution  
y_ext=@(x) log(abs(sec(x)));

    fprintf('\tThe exact value of y at x=%2.2f is %f\n\n',x_max,y_ext(x_max))
  
%plotting the function exact and numerical
hold on
plot(x,y)
plot(x,y_ext(x))

%solving using ode45 matlab function
tspan = [0 pi/4];
y0 = 0;
[xx,yy] = ode45(@(x,y) tan(x), tspan, y0);

fprintf('\tThe value of y at x=%2.2f using ode45 is %f\n\n',xx(end),yy(end))

plot(xx,yy,'-o')
xlabel('x')
ylabel('y')
title('x vs. y plot')
legend('RK4 solution','Exact solution','ode45 solution','location','best')

fprintf('Error in RK4 solution with exact solution is %e.\n',norm(y-y_ext(x)))
fprintf('Error in ode45 solution with exact solution is %e.\n',norm(yy-y_ext(xx)))


%%%%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%%

Add a comment
Know the answer?
Add Answer to:
use matlab only please Problem # 1 P-1 Solve the following initial value problem using a4 order RK scheme: dy dx=tan(x), y(0)= 0.0 - Compare your results by calcudating the error andploting with...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT