【问题标题】:My For Loop Initial Conditions Reset Every Iteration我的 For 循环初始条件重置每次迭代
【发布时间】:2018-11-26 17:39:26
【问题描述】:

我正在尝试运行这个 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

【问题讨论】:

  • 对于上下文,ODE 求解器是“ode15s”函数。
  • 我认为是因为在 for 循环开始时,您从 spart 初始化变量,而在循环结束时您更新 sparts。

标签: matlab for-loop


【解决方案1】:

shamalaia 是对的。您应该使用最初分配的相同变量名称: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

【讨论】:

  • @Tom,如果您对答案感到满意,您能接受吗?或者至少给我 +1 说它很有用。也给上面的 shamalaia +1,因为他给出了正确的方向。干杯!
猜你喜欢
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 2018-02-13
  • 2013-11-27
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多