MATLAB: I have this code for Runge Kutta method and keep showing error “index must be a positive interger ” please I need help

najlaa hassan

%Script that demonstrates the Runge-Kutta integration for a first order problem %the problem to be solved is: %f(xi,yi)=(1/2)-xi+2*yi h=0.2; %h is the time step. y0=1; yi=y0; xf=0.2; x0=0; xi=x0; n=xf-x0/xf; %iterate for i=0:n f(xi,yi)=(1/2)-xi+2*yi; k1=f(xi,yi)*h; k2=f(xi+(h/2),yi+h/2*k1); k3=f(xi+h/2,yi+(h/2)*k2); k4=f(xi+h,yi+h*k3); y(i+1)=yi+(1/6)*(k1+2*k2+2*k3+k4); x(i+1)=xi+h;
end
y(i+1)
x(i+1)

Best Answer

Suppose you have the (mathematical) function f(x,y) = 0.5 - x + 2*y. To define this function in MATLAB you can either write an m-file named "f.m" that contains
function z = f(x,y)
z = 0.5 - x + 2*y;
or you can define it like so
f = @(x,y) 0.5 - x + 2*y;
The thing on the left of the equals sign is a variable name, in this case "f". The thing on the right of the equals sign is an "anonymous function". The @(x,y) part signals that what follows is a function of x and y and that the value for any other unknowns (which there are none in this case) should be considered constant with whatever values they happen to have in your MATLAB session at the moment the function is defined. For example,
>> c = 1;
>> f = @(x,y)c - x + 2*y;
>> c = 2;
>> g = @(x,y)c - x + 2*y;
>> f(0,0)
ans =
1
>> g(0,0)
ans =
2
Note that changing the value of c after the function f was defined did not change the value of c used in it.
I don't know why I bothered to explain the use of constant parameters, but I figure you're bound to need that at some point.