Effacer les filtres
Effacer les filtres

Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

reducing time in using for-loop

1 vue (au cours des 30 derniers jours)
Ronaldo
Ronaldo le 26 Nov 2013
Clôturé : MATLAB Answer Bot le 20 Août 2021
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

Réponses (1)

Roger Stafford
Roger Stafford le 27 Nov 2013
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.

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by