extracting sub matrix - time consuming
2 次查看(过去 30 天)
显示 更早的评论
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
2011-8-6
A mex routine could avoid unnecessary intermediate data copies. Could you list the dimensions of *all* of your variables?
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!