Help running a while loop?

조회 수: 1 (최근 30일)
Elizabeth Jurgensen
Elizabeth Jurgensen 2019년 6월 12일
편집: 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