Isn't vectorization more efficent than looping?
Show older comments
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 Comments
James Tursa
on 9 Dec 2020
Edited: James Tursa
on 9 Dec 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
on 9 Dec 2020
Edited: Aziz Kavas
on 9 Dec 2020
Stephen23
on 10 Dec 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
on 10 Dec 2020
Walter Roberson
on 10 Dec 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.
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!