Summing output of for loop.

I have a for loop producing an n x m matrix E fr every time the for loop runs. But i then need to sum all the output matrices from the for loop. Can anyone suggest how to do this. -I dont need to save the individual matrices, just the sum of them. Thanks

1 件のコメント

Jan
Jan 2012 年 4 月 30 日
What have you tried and which problem has occurred? Actually the procedure is trivial: Create the new matrix in each iteration and sum it up.

サインインしてコメントする。

回答 (1 件)

Geoff
Geoff 2012 年 4 月 30 日

2 投票

I gather you have the following situation, or something similar.
nloops = 100;
sumE = zeros(n,m);
for i = 1:nloops
% This loop generates a new E
E = [];
for j = 1:n*m
% magic goes here
end
% Now you want to sum E
sumE = sumE + E;
end
Well, the answer is contained above. =)

5 件のコメント

Jan
Jan 2012 年 4 月 30 日
Instead of "E=[]" a proper pre-allocation is recommended: "E=zeros(n, m)".
Dougie
Dougie 2012 年 4 月 30 日
This all makes sense apart from the:
for j = 1:n*m
% magic goes here
end
is this just meant to be the calculation for E?
Thanks
Geoff
Geoff 2012 年 5 月 1 日
Yes, you stated that you already had a loop to compute E, so I slapped in a magical loop to compute E as a placeholder. And yes, as per Jan Simon's reminder, I would usually preallocate the array instead of declare it empty.
Jan
Jan 2012 年 5 月 2 日
@Dougie: If you had posted the relevant part of your program, Geoff wouldn't has to guess the part for calculating E.
Beside the tiny detail of the pre-allocation, Geoff's solution seems to be optimal. +1
Tilkesh
Tilkesh 2017 年 4 月 14 日
Yes really it is magic

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

質問済み:

2012 年 4 月 29 日

コメント済み:

2017 年 4 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by