필터 지우기
필터 지우기

extracting sub matrix - time consuming

조회 수: 1 (최근 30일)
lital
lital 2011년 8월 6일
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
James Tursa
James Tursa 2011년 8월 6일
A mex routine could avoid unnecessary intermediate data copies. Could you list the dimensions of *all* of your variables?
lital
lital 2011년 8월 6일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Sean de Wolski
Sean de Wolski 2011년 8월 6일
  • 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
lital
lital 2011년 8월 6일
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 2011년 8월 6일
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).

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by