# how to use MATLAB function? T^T

• posted

function [x, y] = rk4 (f, tspan, y0, h)
a = tspan(1); b = tspan(2); n = (b-a) / h;
x = (a+h: h : b);
k1 = h * feval(f, a, y0);
k2 = h *
feval(f, a + h / 2, y0 + k1 / 2);
k3 = h * feval(f, a + h / 2, y0 + k2 / 2);
k4 = h * feval(f, a + h, y0 + k3);
y(1) = y0 + k1/6 + k2/3 + k3/3 + k4/6;
for i= 1 : n-1
k1 = h * feval(f, x(i), y(i) );
k2 = h *
feval(f, x(i) + h/2, y(i) + k1 / 2);
k3 = h * feval(f, x(i) + h/2, y(i) + k2 / 2);
k4 = h * feval(f, x(i) + h, y(i) + k3);
y(i+1) = y(i) + k1/6 + k2/3 + k3/3 + k4/6;
end
x = [ a x ];
y = [ y0 y];
function y = f(p, q)
y = exp(p) + q;
end
rk4.m, and f.m...
Use RK 4th order numerical method, solve that function..
I type at command window
> rk4(f, [0 3], 0, 0.5)
??? Input argument "p" is undefined.
Error in ==> f at 2
y = exp(p) + q;
and,
> rk4(f(0, 0), [0 3], 0, 0.5)
??? Error using ==> feval
Argument must contain a string or function_handle.
Error in ==> rk4 at 6
k1 = h * feval(f, a, y0);
Initial value is (0,0), and original function is y'=y+e^t