Optimizing a 'for' loop
3 次查看(过去 30 天)
显示 更早的评论
%%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 个评论
采纳的回答
Geoff
2012-4-11
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.
更多回答(1 个)
Matt Kindig
2012-4-11
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?
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Linear Least Squares 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!