dee
dee

Reputation: 89

How do I store a changing variable obtained from an iteration, to use it in future iterations?

I am trying to store a variable in an iteration once certain conditions are met. The stored variable will be used in future iterations and reset once the condition is no more met. For example:

Any help will be extremely appreciated!

Upvotes: 0

Views: 87

Answers (1)

Trogdor
Trogdor

Reputation: 1346

I'm not sure if this meets the exact needs, but here's an attempt.

I introduced two variables, freeze and lastval. I use freeze to signify using the previous value for m(k,i) instead of recalculating it. lastval simply stores the most recently calculated value for reuse.

freeze = false;
for k=1:200
    for i=1:49
        if d_p(i)<rp
            if not(freeze)
                m(k,i)= y(k,i)/x(k,i); %given previous values of x,y
                freeze = true;  
                lastval = m(k,i);
            else
                m(k,i) = lastval;
            end

            u1(i,k)= x(k,i)+cosd(a_s(i,k))/m(k,i) + sind(a_s(i,k));    %matrix a_s is known.
            u2(i,k)= -4*(y(k,i)+x(k,i)/m(k,i)) -3*(theta_s(i,k)-90);
        else
            freeze = false;
            u1(i,k)=0;
            u2(i,k)=0;
        end
    end
    x(k+1,:)=x(k,:)+u1(:,k).*cosd(a_s(:,k))';
    y(k+1,:)=y(k,:)+u2(:,k).*sind(a_s(:,k))';
end

Upvotes: 1

Related Questions