[Scilab-users] need a more efficient and faster code: suggestions welcome

Heinz Nabielek heinznabielek at icloud.com
Wed Jan 31 00:12:55 CET 2018


Dear friends,
problem [below] is solved, but I need a more efficient and faster code: this is a Monte-Carlo simulation of n random points in a 3d spherical volume of radius r. A typical case is n=20,000 and r=23 mm. And from this, I need the resulting probability distribution of nearest neighbours. 
First attempt with doubly nested for-loops took 6 hours execution time. Version below with more vecctor operations is down to 6 minutes, but suggestions for further improvements would be welcome. 
Greetings
Heinz
 
n=20000;
r=23;
radius = r*grand(n,1,'def').^(1/3);
phi = 2*%pi*grand(n,1, 'def');
costheta = 1 - 2*grand(n,1, 'def');
radsintheta = radius.*sin(acos(costheta));
X = [radsintheta.*cos(phi),radsintheta.*sin(phi), radius.*costheta];
ONE=(ones(1:n-1))';
MinDist=[];
for i=1:n;
    this=X(i,:);XX=X;XX(i,:)=[];
    DIFF=XX-ONE*this;
    MinDist=[MinDist sqrt(min(sum(DIFF.^2,2)))];
end;
jj=-0.05:0.1:3.05;nj=length(jj);
[0.05+jj(1:nj-1)' (histc(jj,MinDist))']
RESULTING OUTPUT
DIST.    PROBABILITY
[mm]
   0.    0.0003 
   0.1   0.0044 
   0.2   0.0202 
   0.3   0.0417 
   0.4   0.06735
   0.5   0.0984 
   0.6   0.12555
   0.7   0.13335
   0.8   0.1357 
   0.9   0.1155 
   1.    0.09735
   1.1   0.0684 
   1.2   0.0438 
   1.3   0.02495
   1.4   0.01385
   1.5   0.00535
   1.6   0.0023 
   1.7   0.00095
   1.8   0.0005 
   1.9   0.00005
   2.    0.00005
   2.1   0. 
   ...  ....
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.scilab.org/pipermail/users/attachments/20180130/70fdbedf/attachment.htm>


More information about the users mailing list