How to avoid for loops using compact array notation?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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 个)
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!