Clear Filters
Clear Filters

Summing output of for loop.

3 views (last 30 days)
Dougie
Dougie on 29 Apr 2012
Commented: Tilkesh on 14 Apr 2017
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 Comment
Jan
Jan on 30 Apr 2012
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.

Sign in to comment.

Answers (1)

Geoff
Geoff on 30 Apr 2012
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 Comments
Jan
Jan on 2 May 2012
@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 on 14 Apr 2017
Yes really it is magic

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!