How might i optimize / vectorize this function?

1 次查看(过去 30 天)
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!

回答(1 个)

Matt J
Matt J 2014-5-16
编辑:Matt J 2014-5-16
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);

类别

Help CenterFile Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by