extracting sub matrix - time consuming
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
James Tursa
le 6 Août 2011
A mex routine could avoid unnecessary intermediate data copies. Could you list the dimensions of *all* of your variables?
Réponses (1)
Sean de Wolski
le 6 Août 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 commentaires
Sean de Wolski
le 6 Août 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).
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!