如何在不使用嵌套函数的情况下求解 ODE? [英] How can I solve an ODE without using nested functions?

查看:23
本文介绍了如何在不使用嵌套函数的情况下求解 ODE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些微分方程需要使用 MATLAB 的 ODE 求解器来求解.虽然微分方程本身相当简单,但它们依赖于很多常数".这些常量不是通用的,需要由调用者提供.

I have some differential equations that I need to solve using MATLAB's ODE solvers. While the differential equations themselves are fairly simple, they depend on a lot of "constants". These constants aren't universal, and need to be supplied by the caller.

此类 ODE 示例如下:

An example ODE of this sort would be:

dx/dt = -j * (k + x) ./ (l + x)

其中 j、k 和 l 是常数,x 是变量.

Where j, k and l are constants and x is a variable.

到目前为止,我一直在解决这些问题的方法是使用一个函数,该函数将所有初始值和常量的所有值(其中大约有 10 个)作为参数,然后调用内部步骤"函数它采用 MATLAB 为其 ODE 求解器所期望的形式的向量.所以...

The way I have been solving these so far is to use a function that takes in all the initial values and all the values of the constants (of which there are around 10) as arguments and then calls an inner "step" function which takes a vector of the form that MATLAB expects for it's ODE solvers. So...

function [outputVector] = someFunction(x, y, j, k, l, m, n, o)
    function [output] = someFunctionStep(t, inputVector)
        x = inputVector(1);
        y = inputVector(2);
        dx = -j .* (k + x) ./ (l + x);
        dy = -m .* (n + y) ./ (o + y);
        output = [dx;dy]
    end
    outputVector = ode15s(@someFunctionStep, [0, endTime], [x,y]);
end

然而,随着变量数量和代码大小的增加,这变得越来越不优雅,并导致几乎无法阅读的代码混乱.所以,我想做的是将每个系统的阶跃函数移动到它自己的文件中,而不必 a) 将常量传递给输入向量中的阶跃函数或 b) 使用全局变量.有没有什么合理的方法可以做到这一点,还是我应该把它搞砸并编写丑陋的代码?

However, as the number of variables and the code size increases, this becomes less and less elegant and results in a damn-near unreadable mess of code. So, what I'd like to do is to move the step function for each system into a file of its own without having to a) pass the constants to the step function in the input vector or b) use global variables. Is there any reasonable way of doing this, or should I just suck it up and write the ugly code?

推荐答案

我建议为您想要解决的每个 ODE 系统创建特定的生成器"函数(基于 Loren 的建议 使用 匿名函数).以下是您的示例的外观:

I would suggest creating specific "generator" functions for each system of ODEs you want to solve (based on Loren's suggestion to make use of anonymous functions). Here's what one might look like for your example:

function odeFcn = makeODE(j,k,l,m,n,o)
  odeFcn = @(t,y) [-j*(k+y(1))/(l+y(1)); -m*(n+y(2))/(o+y(2))];
end

每个生成器函数都会接受一组输入参数并使用它们来创建一个匿名函数,返回 函数句柄 作为生成器函数的输出.以下是您可以使用它的方法:

Each generator function would accept a set of input parameters and use them to create an anonymous function, returning the function handle as an output from the generator function. Here's how you can then use it:

outputVector = ode15s(makeODE(a,b,c,d,e,f), [0,endTime], [x,y]);

这篇关于如何在不使用嵌套函数的情况下求解 ODE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆