arraysmatlabfunction-handle

How to create an array of functions in matlab?


I was trying to solve Lorenz System in matlab by using the method of RK2 and RK4. I had a script for both of the methods, the problem now is how can converge the following

y(1) = @(t,y) 10*(y(2)-y(1));
y(2) = @(t,y) y(1)*(28-y(3))-y(2);
y(3) = @(t,y) y(1)*y(2)-8*y(3)/3;

into simply an column vector of y.

here is what i was hoping for and it never worked:

y = zeros(3,1);
y(1) = @(t,y) 10*(y(2)-y(1));
y(2) = @(t,y) y(1)*(28-y(3))-y(2);
y(3) = @(t,y) y(1)*y(2)-8*y(3)/3;

and following is my RK2 function. my RK4 is similar to this RK2, manybe this can help you understand why I really need an vector of functions.

function y = RK2(fcn,lrange,urange,step,init)
%fcn = vector of functions
%lrange = lower bound
%urange = upper bound
%step = number of steps
%init = initial value

row = size(fcn,1);
stepsize = (urange-lrange)/step;
y = zeros(row,step);
%initializing vector of y
y(:,1) = init;
%initial condition
t = zeros(1,step+1);
%initializing vector of t

if row ~= size(init,1)
    disp('number of functions and number of initial values do not match');
end

for n = 1:step

    t(n) = (n-1)*stepsize;
    t(step+1) = urange;
    y1 = stepsize.*fcn(t(n),y(:,n));
    y2 = stepsize.*fcn(t(n) + stepsize/2, y(:,n) + y1./2);
    y(:,n+1) = y(:,n) + y2;

end

Solution

  • This should work, just make the function output a vector:

    y = @(t,y) [10*(y(2)-y(1)), y(1)*(28-y(3))-y(2), y(1)*y(2)-8*y(3)/3];
    y(1,[1;2;3])
    size(y(1,[1;2;3]))