필터 지우기
필터 지우기

is there any way to vectorize the code to speed up the calculation?

조회 수: 1 (최근 30일)
Chong Tao
Chong Tao 2013년 10월 19일
댓글: Chong Tao 2013년 10월 21일
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
Marc
Marc 2013년 10월 19일
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.
Chong Tao
Chong Tao 2013년 10월 21일
편집: Chong Tao 2013년 10월 21일
I changed my code. it is true, it dosen't take much time for one peak calculation. it is pretty slow, tens of minutes if it is called tens of thousands times.

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2013년 10월 19일
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
Chong Tao
Chong Tao 2013년 10월 21일
편집: Chong Tao 2013년 10월 21일
Thank you Walter. sorry for the later reponse. I tried what you suggested. I used
summation = sum( bsxfun(@times,a,bsxfun(@minus,first,second)), 2);
for the summation instead of repmat. I then tested the speed. It is about twice slower than the original for loop, which suprised me. Is that something you would expect?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by