Reputation: 89
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:
I want keep m(k,i)
constant so that the i
th iteration of the k+1
th iteration is the same, ie: m(k+1,i)= m(k,i)
and y(k,i)
and x(k,i)
keep changing accordingly until the if
condition is NOT met. Then, m(k,i)
resets and re-initiates the sequence if the condition is met again but using the CURRENT y(k,i)
and x(k,i)
to obtain another constant m(k,i)
.
for k=1:200
for i=1:49
if d_p(i)<rp
m(k,i)= y(k,i)/x(k,i); %given previous values of x,y
const = m(k,i);
u1(i,k)= x(k,i)+cosd(a_s(i,k))/const + sind(a_s(i,k)); %matrix a_s is known.
u2(i,k)= -4*(y(k,i)+x(k,i)/const) -3*(theta_s(i,k)-90);
else
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
Any help will be extremely appreciated!
Upvotes: 0
Views: 87
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