Help running a while loop?

3 次查看(过去 30 天)
Elizabeth Jurgensen
编辑: Jan 2019-6-21
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 个评论
dpb
dpb 2019-6-13
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).

请先登录,再进行评论。

回答(2 个)

Chinmay Anand
Chinmay Anand 2019-6-21
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.

Jan
Jan 2019-6-21
编辑:Jan 2019-6-21
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')

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by