Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
is vectorizing this loop possible?

Subject: is vectorizing this loop possible?

From: Andre

Date: 9 Mar, 2012 09:58:17

Message: 1 of 2

who can help me? I don't see the solution (if there is any).
Is it possible to vectorize this loop in where every time the closest of all points Q(i) to one point P(i) is looked for. It would help a lot, because there sometimes are a million points P and a few hundred points Q.

points P(i): xm = [2;5;3;8;5;9;2;7] , ym = [3;5;4;9;1;3;5;1]
points Q(i): xu = [3,2,8] , yu = [1,4,6]

for i = 1:length(xm)
    [fMinDistance, iUsisRow] = min ( sqrt( (xm(i) - xu(:)).^2 + (ym(i) - yu(:)).^2) ) ;
end

thanks in advance

Subject: is vectorizing this loop possible?

From: Roland

Date: 9 Mar, 2012 10:37:12

Message: 2 of 2

"Andre " <andre.donkerbroek@raildata.nl> wrote in message <jjck7p$nnk$1@newscl01ah.mathworks.com>...
> who can help me? I don't see the solution (if there is any).
> Is it possible to vectorize this loop in where every time the closest of all points Q(i) to one point P(i) is looked for. It would help a lot, because there sometimes are a million points P and a few hundred points Q.
>
> points P(i): xm = [2;5;3;8;5;9;2;7] , ym = [3;5;4;9;1;3;5;1]
> points Q(i): xu = [3,2,8] , yu = [1,4,6]
>
> for i = 1:length(xm)
> [fMinDistance, iUsisRow] = min ( sqrt( (xm(i) - xu(:)).^2 + (ym(i) - yu(:)).^2) ) ;
> end
>
> thanks in advance

i dont have now matlab at my hands, but yes, it is possible.
the command "repmat" is your friend

you could create two 3D matrixes out of the points of P and Q of size [2 (for x and y), #points P, #points Q].

Then something like
sqrt(sum((P_3D-Q_3D).^2,1))
will give you the distances.

if that is not clear (which i guess is the case), i can post a sample code later that day.

my only doubt would be, if P and Q are already very large, that P_3D and Q_3D would get too large, in that case you would have to subdivide the size of the matrixes and again use loops.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us