在使用Runge-Kutta四阶的解决方案中使用插值函数外定义

时间:2019-04-08 13:40:46

标签: matlab interpolation anonymous-function runge-kutta

我已经编写了MATLAB代码来解决以下微分方程组。

enter image description here
enter image description here enter image description here z 2 = x 2 +(1+ a x 1

a = 2;
k = 1+a;  
b = 3;
ca = 5;
cb = 2; 

theta1t = 0:.1:10;
theta1 = ca*normpdf(theta1t-5);

theta2t = 0:.1:10;
theta2 = cb*ones(1,101);

h = 0.05;
t = 1:h:10;

y = zeros(2,length(t));  

y(1,1) = 1;  % <-- The initial value of y  at time 1
y(2,1) = 0;  % <-- The initial value of y' at time 1

f = @(t,y) [y(2)+interp1(theta1t,theta1,t,'spline')*y(1)*sin(y(2));
            interp1(theta2t,theta2,t,'spline')*(y(2)^2)+y(1)-y(1)-y(1)-(1+a)*y(2)-k*(y(2)+(1+a)*y(1))];

for i=1:(length(t)-1)  % At each step in the loop below, changed y(i) to y(:,i) to accommodate multi results
   k1 = f( t(i)      , y(:,i)         );
   k2 = f( t(i)+0.5*h, y(:,i)+0.5*h*k1);
   k3 = f( t(i)+0.5*h, y(:,i)+0.5*h*k2);
   k4 = f( t(i)+    h, y(:,i)+    h*k3);
   y(:,i+1) = y(:,i) + (1/6)*(k1 + 2*k2 + 2*k3 + k4)*h; 
end 

plot(t,y(:,:),'r','LineWidth',2);
legend('RK4');
xlabel('Time')
ylabel('y') 

现在要做的是在函数定义之外定义插值/外推,如

theta1_interp = interp1(theta1t,theta1,t,'spline');
theta2_interp = interp1(theta2t,theta2,t,'spline');
f = @(t,y) [y(2)+theta1_interp*y(1)*sin(y(2));
           theta2_interp*(y(2)^2)+y(1)-y(1)-y(1)-(1+a)*y(2)-k*(y(2)+(1+a)*y(1))];

但这给出了错误 enter image description here

请提出解决此问题的方法。

1 个答案:

答案 0 :(得分:2)

请注意,在您的原始代码中:

def bbox_transform_inv(boxes, deltas):

   if boxes.shape[0] == 0:
       return np.zeros((0, deltas.shape[1]), dtype=deltas.dtype)

f = @(t,y) [y(2)+interp1(theta1t,theta1,t,'spline')*y(1)*sin(y(2)); interp1(theta2t,theta2,t,'spline')*(y(2)^2)+y(1)-y(1)-y(1)-(1+a)*y(2)-k*(y(2)+(1+a)*y(1))]; 的调用使用输入变量interp1。此匿名函数内部的t与外部函数中的t不同,后者被定义为向量。

这意味着,当您这样做

t

然后theta1_interp = interp1(theta1t,theta1,t,'spline'); 是一个向量,其中包含所有theta1_interp的内插值,而不仅仅是一个。解决此问题的一种方法是创建更多匿名函数:

t

尽管这并不能真正改善您的代码。