Info

この質問は閉じられています。 編集または回答するには再度開いてください。

reducing time in using for-loop

1 回表示 (過去 30 日間)
Ronaldo
Ronaldo 2013 年 11 月 26 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Below is the code I wrote to calculate the minimum distance of some points (shown by "A") from some lines made by pairs of points (Shown by "B1" and "B2"). I used arrayfun to compute the distance of each A point to all lines. Unfortunately using for loops to apply the arrayfun to all the A points makes the code too sluggish. I was wondering if there is anyway that I can make the code run faster (I am aware of parfor and spmd).
A=importdata('1.txt'); %This file contains two rows of the x and y of each point
B=importdata('2.txt'); %This file contains four rows of the x and y of the two points which make the line
B1=[B(:,1) B(:,2) zeros(size(B,1),1)]; %This line is not important/relevant to my question
B2=[B(:,3) B(:,4) zeros(size(B,1),1)]; %This line is not important/relevant to my question
Distance=zeros(size(A,1),1);
Bcounter=1:size(B,1);
for i=1:size(A,1)
x=A(i,1);
y=A(i,2);
p=[x y zeros(size(A,1),1)]; %This line is not important/relevant to my question
Distance(i,1)=min(cell2mat(arrayfun(@(Bcounter) Distance(p(i,:), B1(GBcounter,:), B2(GBcounter,:)), Bcounter, 'UniformOutput', false))); % Calculate nearest distance of p to line made by B1 and B2 points
end

回答 (1 件)

Roger Stafford
Roger Stafford 2013 年 11 月 27 日
Why not try a direct computation with the data rather than using 'arrayfun'.? It just might be faster.
X = A(:,1);
Y = A(:,2);
X1 = B(:,1); % I assume that B(:,1) & B(:,2) are x and y coordinates of one end of lines
Y1 = B(:,2);
X2 = B(:,3); % and that B(:,3) & B(:,4) are x and y coordinates of the opposite ends
Y2 = B(:,4);
L = sqrt((X2-X1),^2+(Y2-Y1).^2);
P = (X2-X1)./L;
Q = (Y2-Y1)./L;
R = (X1.*Y2-Y1.*X2)./L;
D = zeros(size(A,1),1);
for k = 1:size(A,1)
D(k) = min(abs(P*Y(k)-Q*X(k)+R));
end
Also I assume that distance here is measured to the closest point on an extended line, not just to the line segment.

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by