简单的matlab函数中未定义的变量

Variable undefined in simple matlab function

我不明白为什么会收到以下错误:

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

对于这个函数:

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)

显然我是 Matlab 的初学者,非常感谢任何帮助。

当你这样做时

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

您在调用 odefun 时没有参数。您需要传递函数句柄:

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