Email: Andrew.Knyazev[at]ucdenver.edu
%Note that function RK4step is contained in RK4.m!! %Function RK4.m ends with "% end of m-file RK4.m"should be removed.
close all; clear all;
Example3=inline('sin(xn.^2)','xn','yn') %inline function
[x1,y1]=RK4(Example3,[0,1],1,1.0);
[x2,y2]=RK4(Example3,[0,1],1,0.5);
[x3,y3]=RK4(Example3,[0,1],1,0.1);
plot(x1,y1,'r:');
hold on
plot(x2,y2,'b-')
plot(x3,y3,'g-.')
axis([-7,7,-0.5,2.5])
xlabel('x');ylabel('y');
title('dy/dx=sin(x2); dotted is h=1.0, dashed is h=0.5,dot-dash is h=0.1');
hold off
The figure does not look good.
%Computer Code 3.4: Numerically solving a higher-order %differential equation with fourth-order Runge-Kutta method and %built-in commands; plotting this solution %Example1.m function f=Example1(xn,yn) % %The original ode is 2*x*y’’(x) +x∧2*y’(x)+3*x∧3*y(x)=0 %The system of first order equations is %u1’=u2 %u2’=(-x/2)*u2-((3*x∧2)/2)*u1 % %We let yn(1)=u1, yn(2)=u2 % f= [yn(2); (-xn/2)*yn(2)-((3*xn∧2)/2)*yn(1)]; %Example2.m function f=Example2(xn,yn) %The original ode is y∧(4)(x)+ x∧2*y’(x)+y(x)=cos(x) %The system of first order equations is %u1’=u2 %u2’=u3 %u3’=u4 %u4’=-x∧2*u2-u1+cos(x) % %We let yn(1)=u1, yn(2)=u2, yn(3)=u3, yn(4)=u4 f= [yn(2); yn(3); yn(4); -xn∧2*yn(2)-yn(1)+cos(xn)]; % x0=1; xf=5; y0=[2, 0]; [x1,y1]=ode45(’Example1’,[x0,xf],y0); %Alternatively: [x1,y1]=RK4(’Example1’,[x0,xf],y0,.05); subplot(211),plot(x1,y1(:,1)) xlabel(’x’); ylabel(’y(1)’); subplot(212),plot(x1,y1(:,2)) xlabel(’x’); ylabel(’y(2)’); t=length(x1); y1(t,:) %shows the entries of y1 corresponding to the figure x0=0; xf=5; y0=[1, 0, 0, 1]; [x1,y1]=ode45(’Example2’,[x0,xf],y0); %Alternatively:[x2,y2]=RK4(’Example2’,[x0,xf],y0,.05); plot(x2,y2) legend(’y(1)’,’y(2)’,’y(3)’,’y(4)’) xlabel(’x’); ylabel(’y(1), y(2)’);
Computer Code 4.1: Finding all roots of a polynomial MATLAB, Maple, Mathematica MATLAB >> p=[1 -4 1 6] %these are the coeff of the poly Why not p=[1 -4 1 6] %these are the coefficients of the polynomial or shorter p=[1 -4 1 6] %the coefficients of the polynomialThe same in CC 4.2.