jaslibra
jaslibra

Reputation: 131

Variable undefined in simple matlab function

I cannot understand why I am receiving the following error:

error: 'y' undefined near line 7 column 22
error: execution exception in odefun.m

For this function:

function s = odefun(t, y)
        global K = [ 0.5; 3; 1; 4; 1; 5 ];
        function ret = k(n)
                global K;
                ret = K(n+1);
        end
        s = zeros(6,1);
        s(1) = k(0) -k(1) * y(1) * y(2);
        s(2) = k(2) - k(1) * y(1) * y(2);
        s(3) = k(1) * y(1) * y(2) - k(3) * y(3);
        s(4) = k(1) * y(1) * y(2) - k(2) * y(4);
        s(5) = k(3) * y(3) - k(4) * y(5);
        s(6) = k(3) * y(3) - k(5) * y(6);
end

y0 = [1; 1; 1/2; 0; 0; 0]
[t, y] = ode45(odefun, [0 10], y0)

Obviously I am a beginner with Matlab and any help is much appreciated.

Upvotes: 0

Views: 230

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60504

When you do

[t, y] = ode45(odefun, [0 10], y0)

you are calling odefun without arguments. You need to pass the function handle:

[t, y] = ode45(@odefun, [0 10], y0)

Upvotes: 2

Related Questions