MATLAB: Storing values form a while loop within a for loop.

for loopMATLABwhile 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?

Best Answer

for (ii) =
That is not a valid matlab syntax
Q(k) = k
Well, that just store the value of k at index k, so Q will end up as Q = [1 2 3 4 5 6 ...]. Note that if k is greater than 100, it will resize your predeclared Q so that it has k elements.
I think you meant to have
Q(ii) = k; %note that using Q(1, ii) is pointless, since Q is a vector
And of course
W = mean(Q(1,k));
calculates the mean of just one element of Q (whichever k was reached on the 100th iteration of the for loop). You probably meant
W = mean(Q);
Note that using variable names that have meaning would avoid confusion over what ii and k stand for, e.g:
stepbyrepeat = zeros(1, 100);
for repeat = 1:100
step = 0;
%... while ...
stepbyrepeat(repeat) = step;
end
And finally, do not use sum as a variable name. It prevents you from using the sum function.
Related Question