Storing values from a while-loop within a for-loop.

Hi, I've tried to run a while loop a hundred times with a for loop. My goal is to store the counting variable (k) from each while-loop In a vector, and then take the mean of this vector. I've coded it this way;
Q = zeros(1,100);
for (ii) = 1 : 100
k = 0 ; %counting variabel
sum = 0;
critical_value = 1.9;
while sum<critical_value
sum = rand(1) + rand(1) ;
k = k + 1;
end
Q(1,k) = k;
end
W = mean(Q(1,k));
My problem is that the values I try to store don´t really make sense compared to what I intended it to be. The end goal of this project is to test the mean of the stored counting variables against an predetermined expected value.
Do anyone have a suggestion on how to solve my problem?

Respuestas (1)

Geoff Hayes
Geoff Hayes el 19 de Oct. de 2017
Børge - your code seems to be counting the number of iterations (of the while loop) it takes to generate two random number whose sum is greater than 1.9. A problem may be how you update Q
Q(1,k) = k;
If on ii=1, it takes 24 times to generate this sum (please rename this variable as sum is a built-in MATLAB function) then you are setting the 24th element of Q to 24. Wouldn't you rather have
Q(ii) = k;
where we set the ii th iteration to be k.
Once you have done this for 100 iterations, you have an array Q of 100 iteration counts. To find the mean, you would do
mean(Q)
instead of what you are doing which just returns the last element in your array
Or have I misunderstood how you want to compute the mean?

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 19 de Oct. de 2017

Respondida:

el 19 de Oct. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by