필터 지우기
필터 지우기

cumulative sum in a loop

조회 수: 4 (최근 30일)
Joseph Lee
Joseph Lee 2017년 10월 20일
편집: Andrei Bobrov 2017년 10월 23일
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
Rik
Rik 2017년 10월 20일
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 2017년 10월 23일
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.

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

채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 10월 23일
편집: Andrei Bobrov 2017년 10월 23일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by