[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Vectorizing loops
From: |
marco atzeri |
Subject: |
Re: Vectorizing loops |
Date: |
Thu, 12 Jan 2012 21:18:20 +0100 |
User-agent: |
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0) Gecko/20111222 Thunderbird/9.0.1 |
On 1/12/2012 8:59 PM, andrewcd wrote:
Bumping an old thread of mine with a new (similar) question. I hope I'm not
being a pest, but I'm an occasional user at best -- I mostly work in stata,
but occasionally I need to do simulations (or huge-N stats).
My problem: I'm trying to simulate diffusion of a thing in space, and to do
that I need to calculate the Euclidian distance between all of the nodes. I
have it below in loop format. it is slow enough with 1000 units, but I want
to bring it to 1 million once I get the rest of the code finished. Any
hints on how I could vectorize this particular loop?
Many thanks, muchas gracias, asante sana.
peeps=1000
%Procedure
%1) Define Space
x = 100
y = 100
%2)Define units
folks = ones(peeps,1)
%-Give these folks coordinates
folks(:,2) = rand(peeps,1)*x;
folks(:,3) = rand(peeps,1)*y;
%3) Define distances between dudes
for i = 1:peeps
for j = 1:peeps
dist(i,j) = (abs(folks(i,2)-folks(j,2)).^2 +
abs(folks(i,3)-folks(j,3)).^2).^.5;
end end
--
for peeps = 1e6 , I guess you will run out of memory as dist size
will be 1e12
With next 3.6.0 broadcasting
folks = [ones(peeps,1), rand(peeps,1)*x, rand(peeps,1)*y];
dist = sqrt((folks(:,2)-folks(:,2)').^2 + (folks(:,3)-folks(:,3)').^2 ));
Regards
Marco