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

2 次查看(过去 30 天)
This is how i try it
for i=1:23;
a(i) = randn(1);
a = a + a(i);
end

采纳的回答

Adam Danz
Adam Danz 2020-3-24
"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 个评论
Adam Danz
Adam Danz 2020-3-24
FYI, you don't need a loop to do this. See the last line of my answer for a non-loop method.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by