How to vectorize a for loop?
6 views (last 30 days)
Show older comments
How can i make that code run faster?
data_file=importdata('Hz.txt');
xA=data_file(:,1);
yA=data_file(:,2);
zA=data_file(:,3);
[ndat,yyy]=size(xA); #ndat=540
aA=1./(xA+1); %Number of randoms Ran=10000;
X1=randi([-100,150],[1,Ran])/100;
s1=randi([-100,150],[1,Ran])/100;
s2=randi([-100,150],[1,Ran])/100;
sw=randi([50,130],[1,Ran]);
T=zeros([ndat,Ran]);
H=zeros([ndat,Ran]);
XsA=zeros([1,ndat]);
Chit=zeros([1,Ran]);
t=0:0.0000000001:0.04;
for j=1:Ran
x1=X1(j);
y1=s1(j);
y2=s2(j);
w=(sw(j));
x2=-x1-1/4*y1^2-3/2*y1*y2-1/4*y2^2;
As=x1*y1*y2*exp(-w*t)+x2;
for i=1:ndat
dA=abs(As-aA(i));
[v T(i,j)]=min(dA);
I=T(i,j);
H(i,j)=x1*y2+exp(-w*t(I))+exp(x2);
XsA(i)=(H(i,j)-yA(i)).^2 ./(zA(i).^2);
Chit(j)=sum(XsA);
end
end
end
1 Comment
Jan
on 6 Sep 2012
Edited: Jan
on 6 Sep 2012
An optimization needs a look in the profiler (although this disables the important JIT!) and the possibility to run the code. Even advanced programmers cannot predict, how the JIT will handle modifications of the code. Therefore it would be helpful, if you provide test data. E.g. RAND with a fixed seed is a good and cheap method in the forum - if such data are valid for the tests.
Accepted Answer
Jan
on 6 Sep 2012
Edited: Jan
on 6 Sep 2012
At first follow the standard rule to avoid all repeated calculations by moving them befor the loop:
c1 = exp(-w * t);
c3 = 1 ./ (zA .^ 2);
for j=1:Ran
x1 = X1(j);
y1 = s1(j);
y2 = s2(j);
w = sw(j);
x2 = -x1 - 0.25 * y1^2 - 1.5 * y1 * y2 - 0.25 * y2^2;
As = x1 * y1 * y2 * c1 + x2;
c4 = x1 * y2 + exp(x2);
for i = 1:ndat
dA = abs(As - aA(i));
[v, I] = min(dA);
T(i,j) = I;
H(i,j) = c4 + c1(I);
XsA(i) = (H(i,j) - yA(i)) .^ 2 .* c3(i);
end
Chit(j) = sum(XsA); % I guess this should be here
end
From this point a vectorizeation would mean to replace "i" inside the loop by "1:ndat".
More Answers (2)
Doug Hull
on 6 Sep 2012
400 Million long vector t seems excessive to me.
What if you make it significantly shorter? I would lower your number of iterations on everything. See if that gives good results. Then start cranking up the number of iterations, and resolution. If it is not fine enough, then run it through the profiler to see where the bottlenecks are. My guess is that doing the above will get the results you need without code changes.
Robert Cumming
on 6 Sep 2012
you over write:
Chit(j)=sum(XsA);
in every i loop - are you sure you want to do that?
Profile the code and you will see which lines are the most expensive.
2 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!