# How might i optimize / vectorize this function?

2 views (last 30 days)
Tyler on 16 May 2014
Edited: Matt J on 16 May 2014
I have been using the function:
to find the distance between two lines.
However, i would like to find the distance between 1 line and say, 100,000 different lines. I will be performing this computation over many iterations and i am finding looping 1 by 1 100,000 times each iteration is significantly increasing the time of what i am trying to do.
I had thought maybe to create a matrix of the one i am trying to check (so 100,000 copies of hte same line) to compare with the corrseponding 100,000 other lines and found that this code doesnt lend itself to matrix inputs - there is a line in the code (40 i believe which has a ^2 term which produces a NxN matrix of NaN)
Anyone have any idea how to use the basic checking in this code (i.e. distance between two lines) but check 1 line vs 100,000 lines in an efficient manner?
Any help would be greatly appreciated!
##### 2 CommentsShowHide 1 older comment
Tyler on 16 May 2014
yes, 3D

Matt J on 16 May 2014
Edited: Matt J on 16 May 2014
Assuming the lines are all non-parallel, the following should do it
%Test data
N=1e5;
r0=[0;0;0]; d0=[1;1;1]; %fixed line, parametric equations: r0+t*d0
R=rand(3,N); D=ones(3,N); %other lines, equations: R(:,i)+t*D(:,i)
%Distance computations
tic;
d=l2unitize(d0);
D=l2unitize(D);
distances=abs(sum(cross(repmat(d,1,N),D).*bsxfun(@minus,r0,R)));
toc;
%Elapsed time is 0.010295 seconds.
function n=l2norm(A,varargin)
n=sqrt(sum(A.^2,varargin{:}));
function A=l2unitize(A,varargin)
n=l2norm(A,varargin{:});
A=bsxfun(@rdivide,A,n);