MATLAB Answers

How do I write a loop which creates a random number and adds the previous values

1 view (last 30 days)
Jehona
Jehona on 24 Mar 2020
Commented: Ajay Kumar on 24 Mar 2020
This is how i try it
for i=1:23;
a(i) = randn(1);
a = a + a(i);
end

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
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);
end
However, you don't need a loop. This line does the same thing as the loop above.
a = cumsum(randn(1,n));

More Answers (1)

Ajay Kumar
Ajay Kumar on 24 Mar 2020
Edited: Ajay Kumar on 24 Mar 2020
res_sum = 0;
for i=1:23;
a(i) = randn(1);
res_sum = res_sum + a(i);
end

  4 Comments

Show 1 older comment
Ajay Kumar
Ajay Kumar on 24 Mar 2020
res_sum = 0;
for i=1:23;
a(i) = randn(1);
res_sum(i+1) = res_sum(i) + a(i);
end
the sum will be 1x24 because the first value of sum is 0. You can however delete the first element
res_sum = res_sum(2:end);
Adam Danz
Adam Danz on 24 Mar 2020
FYI, you don't need a loop to do this. See the last line of my answer for a non-loop method.

Sign in to comment.

Sign in to answer this question.