Azzera filtri
Azzera filtri

cumulative sum in a loop

4 visualizzazioni (ultimi 30 giorni)
Joseph Lee
Joseph Lee il 20 Ott 2017
Modificato: Andrei Bobrov il 23 Ott 2017
c = 1;
while c <= 5
i = 1;
while i <= 10,
z = rand(1, 10);
Z(c, i) = z(i) % how to get this to add the previous c=1 if this is c=2 loop to be cumulative sum
end
end
example:
C = 1 Z1 Z2 Z3 Z4 Z5 Z6 Z7 Z8 Z9 Z10
C = 2 Z1 + Z1' Z2+Z2' Z3 + Z3' ( Z' is a new random number)
C = 3 Z1 + Z1'+Z1''
  2 Commenti
Rik
Rik il 20 Ott 2017
Two questions: Why are you using while loops, and why don't you generate a larger random matrix, so you can reference previous values.
Is this a homework question? If it is, could you post the original question as well? And have you looked at how you might be able to tweak a call to cumsum?
Joseph Lee
Joseph Lee il 23 Ott 2017
how do i generate a larger cumulative matrix? this is just a short summary of a part of code for project, for each loop theres calculations involving related equations that uses the random number. I need to generate random number for each loop and to save it at the end, then use it for the next set of loop for cumulative sum.

Accedi per commentare.

Risposta accettata

Andrei Bobrov
Andrei Bobrov il 23 Ott 2017
Modificato: Andrei Bobrov il 23 Ott 2017
Z = rand(10,1,10);
Z_add = randi(5,2,10);
out = cumsum([Z;Z_add]);
with for - loop
m = 5;
Z = randi(20,1,10);
n = size(Z,2);
Z_out = [Z;zeros(m-1,n)];
for ii = 2:m
Z_out(ii,:) = Z_out(ii-1,:) + randi(5,1,n);
end

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by