is there any way to vectorize the code to speed up the calculation?
2 views (last 30 days)
Show older comments
I have a function to calculation some lineshapes which was called thousands of times. it is pretty slow. I'm wondering how to make it run faster.maybe vectorizing the code to eliminate for loop? the relevant code is as following. thanks,
% input variables, x and y, with x =3001 points, fixed length
x= -1.5:0.001:1.5;
y = 1.18;
% function doing the calculation
N = 33;
K = zeros(size(x));
a = zeros(1,N);
summation = 0;
for n = 1:N
a(n) = 2/9*exp(-((n-1)*pi/9)^2);
first = (1i*(n-1)*pi*9+9^2*y)*(1-exp(-(1i*(n-1)*pi+9*y))*cos(9.*x)) + exp(-(1i*n*pi+12*y))*12^2.*x.*sin(9.*x);
second = (1i*(n-1)*pi*9-9^2*y)*(1-exp(1i*(n-1)*pi-9*y).*cos(9.*x)) - exp(-(1i*n*pi+12*y))*12^2.*x.*sin(9.*x);
summation = summation + a(n)*(first - second);
end
third = -(y-exp(-(9*y))*(y.*cos(9.*x)-x.*sin(9.*x)))./(x.^2+y^2);
K = summation - a(1)*third;
2 Comments
Marc
on 19 Oct 2013
What is tau?? I set it to 0.3 arbitrarily and got 0.01 seconds with the profiler (~0.008 to be exact) 2013b, MacOS 64bit. Seems fast to me.
Accepted Answer
Walter Roberson
on 19 Oct 2013
You could use meshgrid() or ndgrid() to create meshes of n and x, and use those meshes in your code.
[xM, nM] = ndgrid(x, 1:N);
a = 2/9 * exp(-((nM-1)*pi/9).^2);
first = (1i*(nM-1)*pi*9+9^2*y).*(1-exp(-(1i*(nM-1)*pi+9*y)).*cos(9.*xM)) + exp(-(1i*nM*pi+12*y))*12^2.*xM.*sin(9.*xM);
second = (1i*(nM-1)*pi*9-9^2*y).*(1-exp(1i*(nM-1)*pi-9*y).*cos(9.*xM)) - exp(-(1i*nM*pi+12*y))*12^2.*xM.*sin(9.*xM);
Now (first - second) will be a matrix rather than a vector. Your code would then become something like
summation = sum( repmat(a, size(xM,1), 1) .* (first - second), 1);
but you might need to transpose "a" or repmat it along the second dimension instead of the first.
1 Comment
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!