How to avoid for loops using compact array notation?
1 view (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
More Answers (1)
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.
See Also
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!