将额外的依赖于迭代的输入传递给 ode45 [英] Passing additional iteration-dependent inputs to ode45
问题描述
我正在尝试使用 ode45
函数求解微分方程.考虑以下代码,
I'm trying to solve differential equation using the ode45
function. Consider the following code,
[t1,X2] = ode45(@(t,x)fun(t,x,C1,C2,C3,C4),t0,X01);
其中参数 C1
、C2
、C3
和 C4
是列向量,它们应该可供ode45
所指的函数 (fun.m
).我希望每次迭代后都改变值,例如,在开始时,我想要的 C1
条目是 C1(1)
,在下一次迭代中它是 C1(2)
等
where parameters C1
, C2
, C3
and C4
are column vectors, which should be available to the function that ode45
is referring to (fun.m
). I want the values to change after every iteration, so for example, at the beginning the entry of C1
I want in is C1(1)
, in the next iteration it's C1(2)
, etc.
我该如何实现?
推荐答案
您可能已经注意到 官方文档 在这种情况下并没有太大帮助(因为它们几乎迫使您使用 global
变量 - 这是可行的,但不鼓励).相反,我将向您展示如何使用类和函数句柄来做到这一点.考虑以下几点:
You may have noticed that the official docs are not too helpful in this scenario (as they pretty much force you to use global
variables - which is doable, but discouraged). Instead, I'll show you how this can be done with classes and function handles. Consider the following:
classdef SimpleQueue < handle
%SIMPLEQUEUE A simple FIFO data structure.
properties (Access = private)
data
position
end
methods (Access = public)
function obj = SimpleQueue(inputData)
%SIMPLEQUEUE Construct an instance of this class
obj.data = inputData;
rewind(obj);
end % constructor
function out = pop(obj, howMany)
%POP return the next howMany elements.
if nargin < 2
howMany = 1; % default amount of values to return
end
finalPosition = obj.position + howMany;
if finalPosition > numel(obj.data)
error('Too many elements requested!');
end
out = obj.data(obj.position + 1 : obj.position + howMany);
obj.position = finalPosition;
end % pop
function [] = rewind(obj)
%REWIND restarts the element tracking
% Subsequent calls to pop() shall return elements from the beginning.
obj.position = 0;
end % rewind
end % methods
end % classdef
这个怎么用?简单:
C1q = SimpleQueue(C1);
C2q = SimpleQueue(C2);
C3q = SimpleQueue(C3);
C4q = SimpleQueue(C4);
[t1,X2] = ode45(@(t,x)fun(t,x,@C1q.pop,@C2q.pop,@C3q.pop,@C4q.pop),t0,X01);
如您所见,在 fun
中,我们使用 C1q()
而不是 C1
.
As you can see, inside fun
we use C1q()
instead of C1
.
这篇关于将额外的依赖于迭代的输入传递给 ode45的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!