Optimizing a 'for' loop
1 回表示 (過去 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!