Azzera filtri
Azzera filtri

optimize inefficient piece of code

5 visualizzazioni (ultimi 30 giorni)
Wesley Ooms
Wesley Ooms il 6 Gen 2014
Commentato: Simon il 7 Gen 2014
I have a piece of code as part of a bigger piece that is inefficient. The code is called many times and is a bottleneck in the proces also according to the matlab profiler. I feel it can be done faster. The code looks as follows
clear all
% initialize variables of interest
% start inefficient code
for it=1:10
I would like to do the for loop in one go (so remove the for loop). l1 and l2 are distances (l1 is norm of p1 and l2 is norm of p2), and p1, p2 are 3d coordinates. The goal of the code is to pick the coordinates of p1, p2 from the one with the smallest distance.
  1 Commento
Wesley Ooms
Wesley Ooms il 6 Gen 2014
Ican do something like this:
which results in a correct answer but it feels like a waste of memory and a lot of unnecessary operations.

Accedi per commentare.

Risposta accettata

Simon il 6 Gen 2014
You can of course avoid the loop with
p3(1:3, ind==1) = p1(:, ind==1);
p3(1:3, ind==2) = p2(:, ind==2);
This avoids the r-lines before the loop as well. Use '~' instead of 'c' if you are not interessted in the value of the 'min' call.
  4 Commenti
Wesley Ooms
Wesley Ooms il 6 Gen 2014
Modificato: Wesley Ooms il 6 Gen 2014
I run the (complete) code in profile viewer. I also use tic toc in a for loop. In both cases your code is indeed the fastest. Strangely the ~ instead of c makes the code slower.
I optimized allready quite a bit. Matlab functions i substituted to decrease cputime are for example circshift, repmat, cross, dot, mean. Why are these handy and very common functions slower than just straightforward implementing raw code?
Simon il 7 Gen 2014
I think because of the overhead, like checking the input for correct type and dimension and things like that. But that implies that you know what you do and what kind of input to your substitutes you have.

Accedi per commentare.

Più risposte (0)


Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by