Filter löschen
Filter löschen

cumulative sum in a loop

4 Ansichten (letzte 30 Tage)
Joseph Lee
Joseph Lee am 20 Okt. 2017
Bearbeitet: Andrei Bobrov am 23 Okt. 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 Kommentare
Rik
Rik am 20 Okt. 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 am 23 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 23 Okt. 2017
Bearbeitet: Andrei Bobrov am 23 Okt. 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

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by