Filter löschen
Filter löschen

Help running a while loop?

2 Ansichten (letzte 30 Tage)
Elizabeth Jurgensen
Elizabeth Jurgensen am 12 Jun. 2019
Bearbeitet: Jan am 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 Kommentar
dpb
dpb am 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).

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Chinmay Anand
Chinmay Anand am 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.

Jan
Jan am 21 Jun. 2019
Bearbeitet: Jan am 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')

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by