extracting sub matrix - time consuming

10 Ansichten (letzte 30 Tage)
lital
lital am 6 Aug. 2011
Hi, I need to perform a certain calculation on a sub matrix, then insert this sub matrix to another matrix. I'm using : to select the submatrix, problem is, it's very time consuming. After running the profiler i see that this two lines take 20+ seconds each (the lines run 1170 time). With 361*4*18 times this code should run I'm looking at several days of computations.
[x,y] = ndgrid(yup:ydown, xleft:xright);
exponent = (xpower(yup:ydown,xleft:xright).*ypower(yup:ydown,xleft:xright)).*exp(-(xc^2 + yc^2 - 2*xc*x- 2*yc*y)./(2*(sigma^2)));
mat(yup:ydown,xleft:xright) = mat(yup:ydown,xleft:xright)+ exponent;
xpower, ypower and mat are 1080*1920 matrices.
thanks!
  2 Kommentare
James Tursa
James Tursa am 6 Aug. 2011
A mex routine could avoid unnecessary intermediate data copies. Could you list the dimensions of *all* of your variables?
lital
lital am 6 Aug. 2011
x and y dimensions change at each run depending on xc and yc
my original needed calculation was:
[x,y] = ndgrid(1:1080, 1:1920);
gauss2d = gauss2d + exp(-((x-xc).^2 + (y-yc).^2)./(2*(sigma^2)));
where xc and yc are scalars that change at each run.
since there is no need for me to this calculation for the entire 1080*1920 matrix (as most of the gauss function will return 0) im only calculating the gauss2d function for a submatrix. (just to be sure i did run this line and it resulted in 300 sec.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sean de Wolski
Sean de Wolski am 6 Aug. 2011
  • Use bsxfun instead of ndgrid, it'll skip the expansions.
  • Do xc,yc and sigma change? If not, calculate them being multiplied by 2 (and squared for sigma) once, save that as a new variable.
  • Did you use the profiler to determine this line is the one slowing you down?
  • How much RAM do you have/are you on a 32 bit system, is it exceeded?
  2 Kommentare
lital
lital am 6 Aug. 2011
sigma does not change.
what changes in each run is x,y,xc,yc.
this code runs 1170 times for a frame and according to the profiler, the last two lines (without ndgrid) take more than 20 sec each to run for a frame.
i have 4 gb ram with a 64bit system and matlab works on 60-70% cpu according to the task manager.
Sean de Wolski
Sean de Wolski am 6 Aug. 2011
Look at using bsxfun for the multiplication (will speed up a bit probably) and remove ndgrid call. Are xc,yc scalar? If so this whole line exp process could be:
exp((-(xc^2+yc^2)+2*bsxfun(@plus,xc*((yup:ydown)'),yc*(xleft:xright)))./(TwoSigSquared))
Now no need for ndgrid which takes time and ram.
Calculate 2*sigma^2 once for a little gain (TwoSigSquared).

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by