Runge-Kutta method for 2x2 IVP?
7 views (last 30 days)
Show older comments
chrisholt34
on 29 Apr 2015
Answered: Philip Caplan
on 30 Apr 2015
I have a code written to input a vector into my RK4 file, but I keep getting all kinds of errors, including "Undefined function 'mtimes' for input arguments of type 'cell'." my code is as follows
function [Y, t] = RK42d(f, t0, T, y0, N)
%the input of f and y0 must both be vectors
%composed of two fuctions and their respective
%intial conditions
%the vector Y will return a vector as well
h = (T - t0)/(N - 1); %Calculate and store the step size
Y = zeros(2,N); %Initialize the X and Y vector
t = linspace(t0,T,N); % A vector to store the time values
Y(:,1) = y0; % Start Y vector at the intial values.
for i = 1:(N-1)
k1 = f(t(i),Y(i));
k2 = f{t(i)+0.5*h, Y(i)+0.5*h*k1};
k3 = f{t(i)+0.5*h, Y(i)+0.5*h*k2};
k4 = f{t(i)+h, Y(i)+h*k3};
Y{i+1} = Y{i} + (h/6)*(k1+ 2.*k2 + 2*k3 + k4);
%Update approximation
end
%%%END FILE %%%
I've tried running it using another .m file, using
f = {@(t,y)(y(1) - 4.*y(2)); @(t,y)(-y(1) + y(2))};
y0 = [1;0];
t0 = 0;
T = 1;
N = 11;
RK42d(@(t,y)f, t0, T, y0, N)
but for some reason it won't work. Any tips?
0 Comments
Accepted Answer
Philip Caplan
on 30 Apr 2015
I have made some modifications to the shapes of the arrays in your code and changed the representation of the system of ODEs as a cell array of function handles to an array of function handles. The code below also demonstrates how "ode45" can be used to solve the problem. Both methods give the same result!
function testODE
f = @(t,y) [y(1)-4.*y(2);-y(1)+y(2)];
y0 = [1;0];
t0 = 0;
T = 1;
N = 11;
[Y,t] = RK42d(f, t0, T, y0, N);
figure;
hold on;
plot(t,Y(:,1),'r');
plot(t,Y(:,2),'b');
sol = ode45(f,[0,1],y0);
plot(sol.x,sol.y(1,:),'go');
plot(sol.x,sol.y(2,:),'ko');
legend('RK42d - y1','RK42d - y2','ode45 - y1','ode45 - y2');
end
function [Y, t] = RK42d(f, t0, T, y0, N)
%the input of f and y0 must both be vectors
%composed of two fuctions and their respective
%intial conditions
%the vector Y will return a vector as well
h = (T - t0)/(N - 1); %Calculate and store the step size
Y = zeros(N,2); %Initialize the X and Y vector
t = linspace(t0,T,N); % A vector to store the time values
Y(1,:) = y0; % Start Y vector at the intial values.
for i = 1:(N-1)
y = Y(i,:)';
k1 = f(t(i),y);
k2 = f(t(i) +0.5*h, y +0.5*h*k1);
k3 = f(t(i) +0.5*h, y +0.5*h*k2);
k4 = f(t(i) +h , y +h*k3);
Y(i+1,:) = y + (h/6)*(k1+ 2.*k2 + 2*k3 + k4);
%Update approximation
end
end
For more information on "ode45", please see
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!