我的For循环初始条件会重置每个迭代

时间:2018-11-26 07:32:26

标签: matlab for-loop

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

1 个答案:

答案 0 :(得分:0)

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