我如何将带有两个参数的odefun传递给ode45? [英] How do I pass ode45 an odefun that takes two arguments?
问题描述
我有一个用例,如下:
在F.m
内部,我有一个函数F
,该函数将2 x 1
矩阵x
作为其参数. F
需要将矩阵kmat
与x
相乘. 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
矩阵,并且tstart
和tend
是正整数):
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
的输入函数必须是具有输入t
和x
的函数(可能是向量,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屋!