考虑一个必须与Matlab中的 ode45 集成的多体动力学系统 . 其中一个系统变量直接依赖于时间 t . 我用函数调用求解器:

[T, solution] = ode45(@(t,y)integrate(t,y),[0 tfinal],[initial variables], options);

据我所知, integrate 的第一个输入是一个自变量,通常表示为 t

function [ x, non_diff_var ] = integrate( t, dx)
(...)
F = Forces( (..), t)
end

一旦我运行模拟,我就可以将 t 作为参数传递给 integrate 中的另一个函数 . 但是,我刚遇到模拟到达结束的情况( tfinal ),之后继续使用空的 t 变量 . 在这一点上,显然,我无法用 t 提供 Forces .

我添加了一些小片段以便了解问题:

t_check = 0;
function [ x, non_diff_var, t_check ] = integrate( t, dx)
    if isempty(t) 
        t = 0.103;
    end
    t_check = [t_check t];

并能够绘制结果 . 可以看出 t 向量与输出 T 的大小不同(这并不让我感到惊讶,因为求解器必须做出不返回输出的中间步骤) . 问题在于水平红线表示58个最后一次迭代(刚到达 tfinal 之后)是用空的 t 值执行的 .

plot of t variable


EDIT:

解算器显然很好,错误就在我身边 - 为模拟的所有时间间隔提供了独立变量 t . 我没注意到在使用 ode45 之后,使用空的第一个参数调用函数 integrate

[T, solution] = ode45(@(t,y)integrate(t,y),[0 tfinal],[initial variables], options);
(...)
for i = 1:length(T)
    [~, non_diff_var] = integrate([] ,solution(i,:)');    % empty t variable while calling integrate
    % [~, non_diff_var] = integrate(T(i),solution(i,:)'); % fixed
end

当我发现问题时,起初我会删除这个问题,但如果有人有类似的问题,这可能是一个检查机会 .