Reputation: 125
I am new to Matlab, and am trying to understand how for
loops would work. Specifically, I wish to generate 100 draws from a standard uniform distribution and calculate the mean each time, and repeat this procedure 500 times. Thereafter, I wish to store the mean in a vector.
One way to achieve this is with:
U = [];
Average = [];
for i = 1:500
U = rand(1, 100);
Average = [Average mean(U)];
U = [];
end
The intuition is straightforward. I create an empty vector for U
and the average. Thereafter, I draw 100 realizations from the standard uniform, calculate the average, store the average, empty the U
vector and repeat. The procedure works, but I just wish to clarify one thing: although this is a for
loop, with i
being the loop variable, i
does not show up in the body anywhere. My question is: if the loop variable does not appear in the body, is the procedure simply repeated the number of times equal to the number of 1 unit increments as specified in the for command?
Upvotes: 1
Views: 586
Reputation: 114230
The line
for i = 1:500
assigns a column of the expression to the variable at each iteration. Since 1:500
is a row vector, i
will take on a scalar value at each iteration. If it were an MxN matrix, i
would be a Mx1 column at each step. The number of columns is what determines the number of Iterations, regardless of what you do with the loop variable.
You are free to do whatever you want with i
, including ignore it. You can even assign stuff to it in fact, but the value at the next iteration will be reset to whatever the loop wants.
The assignment U = [];
before and in the loop is unnecessary. It creates a new empty array, but then discards it immediately when you do U = rand(1, 100);
That assignment by itself is sufficient to discard whatever was stored under the name U
.
The expansion of the average by first setting it with Average = [];
and then updating with Average = [Average mean(U)];
is not recommended. Doing it this way is unnecessarily expensive, because each time you have to reallocate the memory to hold an array of size i
. A better option is to pre-allocate all 500 elements and use i
to store the value you want to the correct index. Something like
Average = zeros(1, 500);
for i = 1:500
Average(i) = mean(rand(1, 100))
end
But of course, as Cris Luengo's comment implied, MATLAB is all about vectorization. It's not often that you really need a loop. The particular operation you seek can be performed by generating all the samples you want into a single 100x500 matrix and averaging along the first dimension.
Average = mean(rand(100, 500), 1)
Upvotes: 2