我正在尝试运行for循环(在Matlab中工作(,每次运行循环时,它都会重置为for循环之前给定的初始条件,而不是下一次迭代采用新的速度和位置值。我该怎么解决这个问题?在每次迭代时,我希望循环采用一个新计算的位置和速度值,该值取自ODE解算器输出的"S"矩阵的最后一行。
%Initial position and velocity
spart = [0.05 0.05 0.];
vpart = [-1.7585E+7 -1.7585E+7 0.];
%The entire time span MUST contain an even amount of indices for program to work!
tstep = 0.1E-8; %Defining time step
tfin = 0.7E-8; %Defining final time
intspan = [0:tstep:tfin]; %Total time span
[introw,intcol] = size(intspan);
Wfor = zeros((3*(intcol)/2),6); %Generates matrix of zeros that the trajectory solver will populate later
index = [0:1:intcol/2-1];
for t = 0:1:intcol-2
%Assigns the numerical values of position and velocity to the following variables
x = spart(1);
y = spart(2);
z = spart(3);
vx = vpart(1);
vy = vpart(2);
vz = vpart(3);
icv = [x; y; z; vx; vy; vz];
%Time span
tspan = [intspan(t+1) ((intspan(t+2)-intspan(t+1))/2)+intspan(t+1) intspan(t+2)];
[T,S] = ode15s(@bdipuniodefun, tspan, icv);
[rownum,colnum] = size(S);
Wfor((1+2*t):(3+2*t),(1:6)) = S;
%Assigns the new velocity and position from the final row of the S matrix
vparts(1) = S(rownum,4);
vparts(2) = S(rownum,5);
vparts(3) = S(rownum,6);
sparts(1) = S(rownum,1);
sparts(2) = S(rownum,2);
sparts(3) = S(rownum,3);
end
沙拉酱是对的。您应该使用与最初分配的变量名称相同的名称:spart&vpart。下次如果可以的话,最好还包括你的函数@bdipuniodefun,以便能够测试你的代码。谢谢
建议的代码:
for t = 0:1:intcol-2
%Assigns the numerical values of position and velocity to the following variables
x = spart(1);
y = spart(2);
z = spart(3);
vx = vpart(1);
vy = vpart(2);
vz = vpart(3);
icv = [x; y; z; vx; vy; vz];
%Time span
tspan = [intspan(t+1) ((intspan(t+2)-intspan(t+1))/2)+intspan(t+1) intspan(t+2)];
[T,S] = ode15s(@(t,y) t-y, tspan, icv);
[rownum,colnum] = size(S);
Wfor((1+2*t):(3+2*t),(1:6)) = S;
%Assigns the new velocity and position from the final row of the S matrix
vpart(1) = S(rownum,4);
vpart(2) = S(rownum,5);
vpart(3) = S(rownum,6);
spart(1) = S(rownum,1);
spart(2) = S(rownum,2);
spart(3) = S(rownum,3);
end