I obtain different performance when I execute equivalent code in MATLAB 7.3 (R2006b). When I operate on scalar variables that are constructed explicitly as such (i.e. operate on dtemp = d(1)), I obtain better performance than when I operate on data that is not explicitly defined as scalar (i.e. dtemp = d, where d = sum(vector)). This can be seen when I run the MATLAB Profiler on the two following pieces of code.
1. Fast code:
average=0;for ii = 1:2000000Dima = (ima(x-f:x+f, y-f:y+f) - ima(nx-f:nx+f, ny-f:ny+f));Dima = Dima(:);Dima = Dima.^2;d = sum(Dima);dtemp = d(1);w = exp(-dtemp * acumh);if(w>0), wmax = w; end;average = average + w*ima(nx,ny);end
2. Slow code
average=0;for ii = 1:2000000Dima = (ima(x-f:x+f, y-f:y+f) - ima(nx-f:nx+f, ny-f:ny+f));Dima = Dima(:);Dima = Dima.^2;d = sum(Dima);dtemp = d;w = exp(-dtemp * acumh);if(w>0), wmax = w; end;average = average + w*ima(nx,ny);end
The only difference between the two pieces of code above is where 'dtemp' is created. However, the lines that come after this assignment significantly longer to execute.
Best Answer