How to save all runs in the while loop

3 visualizaciones (últimos 30 días)
Richard Rogers
Richard Rogers el 11 de Mzo. de 2018
Comentada: Stephen23 el 11 de Mzo. de 2018
I'm trying to figure out how to save every point in my while loop in order to graph it in the comet function. My code looks like:
n = 1
score = 0
while n < 100
n = n + 1
x = randi(2);
if (x == 1)
score = score + 1;
elseif(x == 2)
score = score - 1;
end
end
comet(score)
All it currently does is show what score ends as and i what to plot every point before then as well. What should i change it to to make it keep and plot every prevouis score?

Respuesta aceptada

Von Duesenberg
Von Duesenberg el 11 de Mzo. de 2018
Try this:
allScores = zeros(99,1);
n = 1;
score = 0;
while n < 100
x = randi(2);
if (x == 1)
score = score + 1;
elseif(x == 2)
score = score - 1;
end
allScores(n) = score;
n = n + 1;
end
comet(allScores)
  1 comentario
Stephen23
Stephen23 el 11 de Mzo. de 2018
Given that before the loop starts the number of iterations is already known, a for loop would be a better choice:
score = 0;
allScores = zeros(99,1);
for n = 1:99
x = randi(2);
if x==1
score = score + 1;
elseif x==2
score = score - 1;
end
allScores(n) = score;
end
comet(allScores)
It would also be easy to remove the if:
score = 0;
allScores = zeros(99,1);
for n = 1:99
score = score + 1 - 2*randi(0:1);
allScores(n) = score;
end
comet(allScores)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Sequence and Numeric Feature Data Workflows en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by