Optimizing nested for loop

1 回表示 (過去 30 日間)
mashtine
mashtine 2014 年 8 月 31 日
編集済み: dpb 2014 年 9 月 1 日
I have the following for loop and it take quite a while to complete when I am sure it can be faster. It looks up an input value from the assigned dataset and extracts parameters from the struct based on the bin it falls into. Once these parameters have been selected for, the output is based on a calculation.
nrows = length(inpdata);
ncols = 2:2:12;
for j = ncols;
for i = 1:nrows;
if j == 2
height = 'height10m';
elseif j == 4
height = 'height20m';
elseif j == 6
height = 'height40m';
elseif j == 8
height = 'height80m';
elseif j == 10
height = 'height120m';
elseif j == 12
height = 'height200m';
end
if inpdata(i,j) > 0
param = strcat('params',num2str(length(bin(bin < inpdata(i,j)))));
gusts(i,j) = inpdata(i,j) + (inpdata2.(height).(param)(1,3)*(inpdata(i,j)^(1 + inpdata2.(height).(param)(1,1))));
elseif inpdata(i,2) == 0
param = 'params1';
gusts(i,j) = inpdata(i,j) + (inpdata2.(height).(param)(1,3)*(inpdata(i,j)^(1 + inpdata2.(height).(param)(1,1))));
end
end
end
I am not too sure how to optimize this for more efficiency but does anyone have any suggestions? The profiler shows that it is the strcat and num2str functions that are the main culprits but I am not sure how to optimize them as I need them in the loop.

採用された回答

dpb
dpb 2014 年 8 月 31 日
If that's the significant fraction, you can try
param=sprintf('params%d',length(bin(bin < inpdata)));
instead.
  2 件のコメント
mashtine
mashtine 2014 年 8 月 31 日
that certainly did the trick for the most part! Down from roughly 10 mins to 79 seconds. These minor changes can really alter the memory usage. Thank you dpb
dpb
dpb 2014 年 8 月 31 日
編集済み: dpb 2014 年 9 月 1 日
That much is amazing, indeed...just out of curiosity, how does
param=num2str(length(bin(bin < inpdata)),'params%d');
stack up? That is, giving the explicit format but still using num2str?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by