MATLAB Answers

0

Help running a while loop?

Asked by Elizabeth Jurgensen on 12 Jun 2019
Latest activity Edited by Jan
on 21 Jun 2019
I am trying to run a "while loop" from t = 1 second to t = 1000 seconds. I have set up the following code, but when I hit run, nothing happens but I don't get any errors.
In the loop, I have the slope of the function dA(t), which I want to recalculate each iteration. The goal is to plot the populations A(t) each iteration. Please help?
%Part A: Solve a given decay scheme using Euler's basic method with a time
%step of 0.1 seconds from 0 to 1000 seconds. Plot all populations.
A(1) = 1E10;
t = 1:1001;
dt = 0.1;
while t<=1000
dA(t) = -0.005.*A(t);
A(t)=A(t)+dA(t).*dt;
plot(t,A(t),'bo')
t = t+1;
end

  1 Comment

dpb
on 13 Jun 2019
t = 1:1001;
...
while t<=1000
...
reread the documentation on the definition of expression in a while loop construct and then keep reading including the "Tips" section (I'll grant at least some that information should be in the main help section, not as it is in what appears to be less important material).

Sign in to comment.

2 Answers

Answer by Chinmay Anand on 21 Jun 2019

A(1) = 1E10;
t = 1;
dt = 0.1;
while t<=1000
dA(t) = -0.005*A(t);
A(t+1)=A(t)+dA(t)*dt;
plot(t,A(t),'bo')
hold on
t = t+1;
end
hold off
I think you need to look into the documentation for while loop. You are declaring t as a vector instead of a value. Also
dA(t) = -0.005*A(t); % if A(t) is updated with A(t) and dA(t) alone then both vectors should be predefined.
A(t+1)=A(t)+dA(t)*dt; % So i think you will need A(t-1) to update A(t) or A(t) to update A(t+1)
Also use hold on and hold off to plot points on the same plot.

  0 Comments

Sign in to comment.


Jan
Answer by Jan
on 21 Jun 2019
Edited by Jan
on 21 Jun 2019

Use a for loop if the number of steps is known in advance:
A(1) = 1E10;
dt = 0.1;
for t = 1:1001
dA(t) = -0.005 * A(t);
A(t) = A(t) + dA(t) * dt;
end
Time = (1:1001) * dt;
plot(Time, A, 'bo')

  0 Comments

Sign in to comment.