MATLAB: bsxfun is unclear. Want to speed up the minimum distance between segments

Using MATLAB, Imagine an array of Nx6 numbers that represent N segments with 3 + 3 = 6 starting and ending coordinates.

Suppose I have function Calc_Dist( Segment_1, Segment_2 )one that takes two 1x6 arrays at the input and that after some operations returns a scalar, namely the minimum Euclidean distance between these two segments.

I want to calculate the pair minimum distance between all N segments of my list, but would like to avoid a double loop to do this.

I cannot wrap MATLAB function documentation around , so I cannot do this work. For a minimal example (distance calculation is obviously incorrect): bsxfun

function scalar = calc_dist( segment_1, segment_2 )
         scalar = sum( segment_1 + segment_2 )
end

and main

Segments = rand( 1500, 6 )
Pairwise_Distance_Matrix = bsxfun( @calc_dist, segments, segments' )

, ?

+4
2

, pdist, bsxfun. pdist , :

  • , , 'euclidean', 'hamming' ..

  • , , .

     function D2 = distfun(XI, XJ),

1 -by- N XI, X,     M2 -by- N XJ, X     M2 -by- 1 D2, J th -      XI XJ(J,:).

, , , ( , ), . , . : bsxfun:

function scalar = calc_dist( segment_1, segment_2 )
    scalar = sum(bsxfun(@plus, segment_1, segment_2), 2);
end

,

, , ( ), :

distances = squareform(pdist(segments, @calc_dist));

:

N = 4;
segments = rand(N,6);
distances = squareform(pdist(segments, @calc_dist));

distances =
         0    6.1492    7.0886    5.5016
    6.1492         0    6.8559    5.2688
    7.0886    6.8559         0    6.2082
    5.5016    5.2688    6.2082         0
+3

, "" ( ), . 6 & times; N, , , MATLAB.

:

N = 150000;
Segments = rand(6, N);
Pairwise_Distance_Matrix = Inf(N, N);
for i = 1:(N-1)
        for j = (i+1):N
                Pairwise_Distance_Matrix(i,j) = calc_dist(Segments(:,i), Segments(:,j));
        end;
end;

Minimum_Pairwise_Distance = min(min(Pairwise_Distance_Matrix));

, MATLAB arrayfun, cellfun structfun; bsxfun , .

+3

All Articles