Isn't vectorization more efficent than looping?
Ältere Kommentare anzeigen
As far as I know, vectorized computation works faster than loop. However, the given loop above is working faster than vectorized one. Am I missing sth about subject and is there a better way, namely computationally more efficient way, to extract data from dataset.
best regards.
%loop imp.
for l = 1:length(distVect)
proj(in1,in2) = proj(in1,in2) + distVect(l)*attenuationData(rowData(l),columnData(l));
end
% vector implementation
proj(in1,in2)=distVect*attenuationData( sub2ind(size(attenuationData),rowData,columnData))';
5 Kommentare
James Tursa
am 9 Dez. 2020
Bearbeitet: James Tursa
am 9 Dez. 2020
It is unclear to my why you need to call the sum( ) function ... it looks like you may have an inner product inside of it. Also, can you give us all of the variable sizes involved?
Aziz Kavas
am 9 Dez. 2020
Bearbeitet: Aziz Kavas
am 9 Dez. 2020
Stephen23
am 10 Dez. 2020
"As far as I know, vectorized computation works faster than loop."
No, there is no such simple conclusion. Which is faster depends on the algorithm, the size of the data, the required intermediate arrays, the MATLAB version (JIT engine and also functions can change quite a lot) and no doubt many other factors. Whoever told you that vectorization is faster gave you bad information.
Aziz Kavas
am 10 Dez. 2020
Walter Roberson
am 10 Dez. 2020
Mathworks recommends that you do not use the details of any particular release's JIT compiler, as those details change between releases. They recommend that you should instead write simple code, as simple code is easier for the automated analysis to find optimizations for. They do recommend vectorization, but when that vectorization goes beyond pure arithematic calculations, you can start to lose out... like that equivalent of find() I showed, where the vectorized form required three full-array operations whereas the loop find() form only requires one scan through the full matrix.
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!