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

 채택된 답변

"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));

추가 답변 (1개)

Ajay Kumar
Ajay Kumar 2020년 3월 24일
편집: Ajay Kumar 2020년 3월 24일
res_sum = 0;
for i=1:23;
a(i) = randn(1);
res_sum = res_sum + a(i);
end

댓글 수: 4

thanks Ajay!
Do you know how to write it so that I create each time a random number and add it to the previous so that sum is also 1x23?
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);
FYI, you don't need a loop to do this. See the last line of my answer for a non-loop method.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 3월 24일

댓글:

2020년 3월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by