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

1 visualizzazione (ultimi 30 giorni)
Jehona il 24 Mar 2020
Commentato: Ajay Kumar il 24 Mar 2020
This is how i try it
for i=1:23;
a(i) = randn(1);
a = a + a(i);
end
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Adam Danz il 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)];
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 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Jehona il 24 Mar 2020

Accedi per commentare.

### Più risposte (1)

Ajay Kumar il 24 Mar 2020
Modificato: Ajay Kumar il 24 Mar 2020
res_sum = 0;
for i=1:23;
a(i) = randn(1);
res_sum = res_sum + a(i);
end
##### 4 CommentiMostra 2 commenti meno recentiNascondi 2 commenti meno recenti
Adam Danz il 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.
Ajay Kumar il 24 Mar 2020

Accedi per commentare.

### Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by