Any recommendation how to vectorize this double for loop?
Informazioni
Questa domanda è chiusa. Riaprila per modificarla o per rispondere.
Mostra commenti meno recenti
I am a beginner in Matlab, and I would like to speed up the following:
X = 100;
MA = NaN(X,3);
for looper = 1:X
compareDist = inf;
array = MM(looper,:);
for looper2 = 1:size(array,1)
currPoint = cell2mat(C(looper,looper2));
currDist = distancePoints3d(pP, currPoint);
if(~isnan(currPoint(1))&&currDist<compareDist)
compareDist = currDist;
MA(looper,:) = currPoint;
end
end
end
Any help is appreciated. Thanks.
6 Commenti
per isakson
il 30 Ott 2014
What's   C ?
UCL student
il 30 Ott 2014
per isakson
il 30 Ott 2014
Modificato: per isakson
il 30 Ott 2014
Both   "cell"   and   "point"   are ambiguous. And   MM   what's that?
UCL student
il 31 Ott 2014
per isakson
il 31 Ott 2014
"[MM] should not be in the loop."   However, in fact it is:   "array = MM(looper,:)".
Since   looper   is a scalar
array = MM(looper,:);
for looper2 = 1:size(array,1)
reduces to
for looper2 = 1:1
??????
Sean de Wolski
il 31 Ott 2014
How long does it take and how many times do you have to run it?
Risposte (1)
lvn
il 31 Ott 2014
0 voti
A couple of things:
1. If size(MM(looper,:),1) is independent of looper (as you suggest?), you can simply precalculate it before the loops.
2. Depending on your specific data cell2mat(C(looper,looper2)) can be vectorized by precalculating C2=cell2mat(C); be careful with indexing afterwards though (because all will be merged in one large array). Much easier, if C(looper,looper2) all have the same dimension is to get rid of cells altogether and store your C data in higher dimension matrices.
3. Test for ~isnan(currPoint(1)) before calling distancePoints3d, since if it is NaN the output of distancePoints3d is not used.
4. If you have managed to speed up the code, please post the new code, so we can work on the remainder :)
Questa domanda è chiusa.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!