フィルターのクリア

How to avoid for loops using compact array notation?

1 回表示 (過去 30 日間)
Joe
Joe 2013 年 9 月 6 日
I am quite new to Matlab and I don't know how to use compact notation, so I use for loops which slows down the execution time. Any suggestions on how to rewrite the following code in a compact way (array notation) to optimize for execution time?
temperatureData and volumes are 2 matrixes with millions of rows and a few tens of columns. The following code adds the volumes that correspond to certain standard ranges of temperatures (ranges specified in partsLimits).
for o=1:numberBuckets
for m=1:numberRows
for n=1:numberColumns
if (temperatureData(m,n)<=partsLimits(1,o))&&(temperatureData(m,n)>partsLimits(2,o))
standarVolumes(m,o)=standarVolumes(m,o)+volumes(m,n);
end
end
end
end
On the other hand I am not able to use parfor instead of for loops because the standarVolumes variable can not be classified. Any workaround? I hope that I can speed up calculations using the proper notation, but if not possible and I need to keep the for loops I would like to use parfor and parallelize.
Thanks

採用された回答

Image Analyst
Image Analyst 2013 年 9 月 6 日
This should do it faster:
for bucket = 1 : numberBuckets
% Get the min and max for this bucket from partsLimits.
maxValue = partsLimits(1,bucket);
minValue = partsLimits(2,bucket);
% For this bucket, see where the temperatureData
% is within the range [minValue, maxValue]
logicalMatrix = (temperatureData <= maxValue) && ...
(temperatureData > minValue);
% For this bucket, add in volumes that meet the criteria.
standarVolumes(:,bucket)=standarVolumes(:,bucket)+ ...
sum(volumes(logicalMatrix));
end
  1 件のコメント
Joe
Joe 2013 年 9 月 9 日
Thanks for that! this was helpful. Also, this helped solving the parfor issue , now I can use parfor without problems.

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

その他の回答 (1 件)

Doug Hull
Doug Hull 2013 年 9 月 6 日
I find it very unlikely that this will be the bottleneck in your code. Have your run this through the profiler to confirm that of all the code being executed that that this is the part that is best to spend your time speeding up?
It is unclear if these are function calls or matrix indexing operations. That would help to speed this up.
  1 件のコメント
Joe
Joe 2013 年 9 月 9 日
Hi, thanks for your answer. I will definitely run it through the profiler, that's a great idea. It is important to optimize this code as it belongs to a function that the only thing that does is pretty much it, and I need to run it thousands of times...

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

カテゴリ

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