is it possible to do a numerical integration without using a for loop?

3 次查看(过去 30 天)
hi, as you know a "for loop" is very slow operation, as especially if it's a long loop.
is it possible to do a numerical integration without using a for loop? any suggestions?
lamda,ds,dim_s,dim are constants and h is the resaults matrix
s1 = -dim_s:ds1:dim_s;
s2 = -dim_s:ds2:dim_s;
[S1,S2] = meshgrid(s1,s2);
z_t=0;
R_t=0;
x = -dim:lamda/20:dim;
y = -dim:lamda/20:dim;
[Z,R] = meshgrid(x,y);
h= 0;
for zeta = z_0:dz:1
R = S1.*(1-zeta/2)-S2.*(1-3/2*zeta);
h_exp= h+(exp(-((R-R_t).^2+(z*zeta-Z_t)^2)/(2*a^2)))*dz;
end
h = A*h_exp*1i*k*z/2;
h= exp(h_exp);

回答(2 个)

Mischa Kim
Mischa Kim 2014-2-8
One option of avoiding to write your own loop is using one of MATLAB's integrators, e.g., ode45, which, internally, of course also uses a loop. Other than that I am not aware of any non-loop algorithms to solve DE, in general.

Jan
Jan 2014-2-8
编辑:Jan 2014-2-8
No, as far as I know, for loops are not slow. Since Matlab 6.5 for loops are handled efficiently by the JIT acceleration, when you consider some rules, e.g. avoiding eval, avoid changes of the types of variables etc.
Loops are priocessed faster, when you avoid repeated calculations. In you case e.g. (2*a^2) can be calculated once, or the multiplication by dz can be performed after the summing.
I assume there is a typo and you want h_exp= h_exp + ... instead.
The time consuming part of your calculation is not the for loop, but the expensive exp() command. You can reduce the computational time only remarkably, when you find a way to reduce the number of exp() evaluations.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by