How to avoid for loops using compact array notation?

3 views (last 30 days)
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

Accepted Answer

Image Analyst
Image Analyst on 6 Sep 2013
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 Comment
Joe
Joe on 9 Sep 2013
Thanks for that! this was helpful. Also, this helped solving the parfor issue , now I can use parfor without problems.

Sign in to comment.

More Answers (1)

Doug Hull
Doug Hull on 6 Sep 2013
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 Comment
Joe
Joe on 9 Sep 2013
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...

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!