Optimizing a 'for' loop
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
%%Average roughness
for i=1:numel(M)
k= abs((mean(M)-M(i)))/numel(M);
avg=avg+k;
end
With the use of above code, i'm calculating average roughness of a surface. The surface height values are stored in the matrix M. The problem is, it takes half an hour to compute as the matrix is 1024*1280. Any better method to do it? As i have atleast 500 sets of data to compute.
0 comentarios
Respuesta aceptada
Geoff
el 11 de Abr. de 2012
It really takes half an hour??? What hardware are you using?
Anyway, the biggest improvement on this code is to stop calculating the mean of M every time round the loop. Do it once before you loop. That would take your complexity down from O(N*N) to O(N).
Mav = mean(M);
Oh, and of course if M is a matrix then mean(M) is going to be a 1280-length vector. I suppose that takes your current complexity up to just about O(N^3). Do you even get the right answer? Or are you expecting that? I'd have thought you do this:
Mav = mean(M(:));
Next, you could stop dividing by numel(M) every iteration and do it once after the loop:
avg = avg / numel(M);
But then, why not dispense with the loop altogether and let MatLab deal with it?
avg = mean(abs(mean(M(:)) - M(:)));
I bet that'll do your 500 data sets in a couple of seconds flat.
Más respuestas (1)
Matt Kindig
el 11 de Abr. de 2012
You algorithm isn't quite clear. What is the dimension of mean(M)? Why do you subtract M(i) from it each time? Can you clarify the formula for average roughness that you are trying to implement?
Ver también
Categorías
Más información sobre Linear Least Squares en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!