我如何将带有两个参数的odefun传递给ode45? [英] How do I pass ode45 an odefun that takes two arguments?

查看:297
本文介绍了我如何将带有两个参数的odefun传递给ode45?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,如下:

F.m内部,我有一个函数F,该函数将2 x 1矩阵x作为其参数. F需要将矩阵kmatx相乘. kmat是由脚本生成的变量.

Inside F.m I have a function F that takes as its argument a 2 x 1 matrix x. F needs to matrix multiply the matrix kmat by x. kmat is a variable that is generated by a script.

因此,我在脚本中将kmat设置为全局:

So, what I did was set kmat to be global in the script:

global kmat;
kmat = rand(2);

F.m中:

function result = F(x)
    global kmat;
    result = kmat*x;
end

然后,最后,在我拥有的脚本中(已经将x_0定义为适当的2 x 1矩阵,并且tstarttend是正整数):

Then finally, in the script I have (x_0 has already been defined as an appropriate 2 x 1 matrix, and tstart and tend are positive integers):

xs = ode45(F, [tstart, tend], x_0);

但是,这导致了错误:

Error using F (line 3)
Not enough input arguments.

Error in script (line 12)
xs = ode45(F, [tstart, tend], x_0);

这是怎么回事,我该怎么解决?另外,将kmat传递给F的正确方法是什么?

What is going on here, and what can I do to fix it? Alternatively, what is the right way to pass kmat to F?

推荐答案

首先,处理kmat的正确方法是使其成为F.m

Firstly, the proper way to handle kmat is to make it an input argument to F.m

function result = F(x,kmat)
    result = kmat*x;
end

第二,ode45的输入函数必须是具有输入tx的函数(可能是向量,t是因变量,而x是因变量).由于您的F函数没有t作为输入参数,并且还有一个额外的参数kmat,因此在调用ode45

Secondly, the input function to ode45 must be a function with inputs t and x (possibly vectors, t is the dependent variable and x is the dependent). Since your F function doesn't have t as an input argument, and you have an extra parameter kmat, you have to make a small anonymous function when you call ode45

ode45(@(t,x) F(x,kmat),[tstart tend],x_0)

如果您的派生函数是function result=derivative(t,x),那么您只需按照Erik所说的那样执行ode45(@derivative,[tstart tend],x_0).

If your derivative function was function result=derivative(t,x), then you simply do ode45(@derivative,[tstart tend],x_0) as Erik said.

这篇关于我如何将带有两个参数的odefun传递给ode45?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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