How do I write a loop which creates a random number and adds the previous values
10 views (last 30 days)
Adam Danz on 24 Mar 2020
"How do I write a loop which creates a random number and adds the previous values?"
To add to the previous value, the loop must start at index #2. See inline comments for details.
% number of iterations
n = 23;
% Always pre-allocate your loop arrays.
% Define the first random value and use NaNs to fill the rest of the array.
a = [randn(1), nan(1,n-1)];
% Create random numbers in loop, start with 2
for i = 2:n;
a(i) = a(i-1) + randn(1);
However, you don't need a loop. This line does the same thing as the loop above.
a = cumsum(randn(1,n));