필터 지우기
필터 지우기

Averaging matrices over time (in for loop)

조회 수: 1 (최근 30일)
William Summers
William Summers 2012년 9월 11일
Hi there, I have a code in which, for each timestep of a for loop, a new matrix is being generated (50x1) (not randomly). Within my for loop, I plot the elements of the matrix, I then set each plot figure as a video frame and save each frame to a new video file.
What I want to be able to do is compute the average values of each element for all of the matrices, so that I have an overall time averaged matrix. I want to plot this with the other plots that are being generated with each timestep.
My code looks something like my example below, it does the job, but it is extremely slow due to the two for loops, one for computing the average, the second creates the video file, they're doing the same thing twice though!! I've also had to copmpute the first matrix outside the first for loop, to do this, which is not ideal. Is there a way of doing this in one for loop, mainly to reduce the run time, or any other way of doing this better? Many thanks in advance.
output = function_which_creates_matrix(inputs,1);
output_tot = output;
for k = 2:n
output = function_which_creates_matrix(inputs,k);
output_tot = output_tot + output;
end
output_av = output_tot./length(2:n);
OBJ = VideoWriter('plotvideo.avi')
open(OBJ);
for k = 2:n
output = function_which_creates_matrix(inputs,k);
plot(output_av);
hold on
plot(output)
hold off
currframe = getframe;
writevideo(OBJ,currframe);
end
close(OBJ);

채택된 답변

José-Luis
José-Luis 2012년 9월 17일
Maybe this could work (counter is not strictly necessary):
counter = 0;
numSteps = 100;
your_average = zeros(50);
for ii = 1:numSteps
your_matrix = rand(50);
your_average = your_average*(counter)./(counter+1) + your_matrix./(counter+1);
counter = counter + 1;
%Do your stuff
end

추가 답변 (0개)

Community Treasure Hunt

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

Start Hunting!

Translated by