Filter löschen
Filter löschen

Speeding up code

2 Ansichten (letzte 30 Tage)
Paul
Paul am 16 Apr. 2012
I am doing a Physics PhD, and working on a code to model the scattering of light off particles. One section of my code in particular takes ages, and I was wandering if anyone would be able to give me some help with how to speed it up. I managed it cut a chunk of time out by replacing two for loops by matrices, using the ndgrid. I thought that I could possibly turn the last two for loops into matrices, possibly by making a 4D matrix, but I can't get my head round if/how this would be done. Anyway here's the section of code:
Probscatt=zeros(Ntheta,Nphi);
[Y,Z]=ndgrid(y,z);
for m=1:Ntheta
for n=1:Nphi
Probscatt(m,n)=(dy*dz)*(sum(sum((abs(cyz)).^2.*(cos(2*pi*(Y*sin(phi(n))*sin(theta(m))+Z*sin(phi(n))*cos(theta(m))))).^2)));
end
end
y and z are vectors, dy and dz are just numbers, and cyz is a matrix with the same dimensions as Y and Z.
If it would help to explain the context: Probscatt is the probability of light scattering at angle theta, phi. The light is scattering off two particles, which are in a 2D space, with coordinates y and z (this is where the Y and Z come from.
Thanks!
  1 Kommentar
Jan
Jan am 16 Apr. 2012
It does not help to explain the context to speed up the code. It would be more helpful, if you add example data and the sizes of the original problems. It matters if Ntheta has 1e4 or 1e7 elements, or if y is 20 or 2e6.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 16 Apr. 2012
Some general rules for efficient code:
  • Avoid repeated calculations, but use temporary variables instead. Here e.g. "cos(theta(m))" is calculated in each iteration, as "2*pi*Y", "sin(theta(m))", etc.
  • Process arrays column-wise. In your code it will be faster to swap the "for m" and "for n" loops, because then in "Probscatt(m,n)" elements neighboring in the memory are written.
  1 Kommentar
Paul
Paul am 19 Apr. 2012
Thanks for your help Jan

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Walter Roberson
Walter Roberson am 16 Apr. 2012
You might want to investigate bsxfun() as it can be faster than using ndgrid
  1 Kommentar
Paul
Paul am 19 Apr. 2012
Thanks for your help Walter

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements 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