How to avoid for loops using compact array notation?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
Image Analyst
am 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
Weitere Antworten (1)
Doug Hull
am 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.
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!