I have a for loop that creates something like this:
first iteration: [1 2 3 4 5 6 7] second iteration: [2 3 4 5 6 7 8] third iteration: [3 4 5 6 7 8 9]
(these aren't my actual values, just an example)
I want my loop to add all of these together at the end. So I would get an output of:
[6 9 12 15 18 21 24]
How can I do this?
Thanks

 채택된 답변

Adam
Adam 2014년 8월 13일
편집: Adam 2014년 8월 13일

2 개 추천

Just pre-size a vector before the for loop as e.g.
result = zeros( 1, 7 );
then inside the for loop:
result = result + newValues;
where newValues are the results calculated in that iteration. Unfortunately Matlab doesn't have a += operator.
That will add them together as you go. If you really want to only do so at the end then you'd have to store an ( n * m ) matrix for n iterations with length m result and then sum along the relevant dimension.

댓글 수: 2

Hail
Hail 2014년 8월 13일
THANKS!
Salman  Tahir
Salman Tahir 2017년 9월 14일
what do you mean by " If you really want to only do so at the end then you'd have to store an ( n * m ) matrix for n iterations with length m result and then sum along the relevant dimension."? what is this process called? Is there a place I can look this up?

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

추가 답변 (2개)

Joseph Cheng
Joseph Cheng 2014년 8월 13일

1 개 추천

there are two methods. if you need to save each iteration then in the for loop save it like below:
for iter = 1:3
%calculations here to get your values A.
A(iter,:) = randi(10,1,7); % my dummy iteration values
end
SumA = sum(A);
if you don't need to save each iteration.
SumA = 0;
for iter = 1:3
%calculations here to get your values A.
SumA = SumA + randi(10,1,7); % my dummy iteration values
end
Salman  Tahir
Salman Tahir 2017년 9월 14일

0 개 추천

what do you mean by " If you really want to only do so at the end then you'd have to store an ( n * m ) matrix for n iterations with length m result and then sum along the relevant dimension."? what is this process called? Is there a place I can look this up?

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

질문:

2014년 8월 13일

댓글:

2017년 9월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by