将值保存在循环内的向量中,并找到保存特定元素的特定循环

Saving values in a vector inside a loop, and finding the specific loop at which a certain element is saved

我有一个代码,通过用 h 离散化 0 和 1 之间的 t 和 s 来计算两条线段之间的最小距离。该代码将 s 和 t 的每个值的距离保存在一个向量中,并在最后选择最小值。

我想找到最小距离对应的t和s。例如,如果最小距离位于 'mindist' 向量中的索引 3000 处,这对应于 t 和 s 的哪个值?

提前致谢! /阿里安

编辑:我还为整个代码提供了一些注释。我对其进行了一些更改,这似乎可以解决问题:

% Start and end points of line segments
P0=[-0.43256 -1.6656 0.12533]; 
P1=[0.28768 -1.1465 1.1909]; 
Q0=[1.1892 -0.037633 0.32729]; 
Q1=[0.17464 -0.18671 0.72579];

% Direction vectors
u=P1-P0; 
v=Q1-Q0;
w0=P0-Q0;

% Dot products
a=dot(u,u);
b=dot(u,v);
c=dot(v,v);
d=dot(u,w0);
e=dot(v,w0);
F=a*c-b^2;

h=0.01;
t=0:h:1;
s=0:h:1;
mindist=[];
for i=1:length(t)
    for j=1:length(s)
        if F==0
            t(i)=e/c;
            mindist(i,j)=norm((P0+s(j)*u)-(Q0+t(i)*v));
        else
            mindist(i,j)=norm((P0+s(j)*u)-(Q0+t(i)*v));
        end
    end
end
[minval,loc]=min(mindist(:));
[i, j] = ind2sub(size(mindist), loc);
minval=norm((P0+s(j)*u)-(Q0+t(i)*v))

最小值=

1.0710

由于 Matlab 的 pdist2() 函数,您不需要嵌套循环。这是一个例子:

h=0.01;

% Random vectors
P0 = [0;0];
Q0 = [0;2];
u  = [1;0];
v  = [0.707 ; -0.707];

t = 0:h:1;  % Do not really need "s"

U = P0+t.*u;
V = Q0+t.*v;
% The lines above work in Matlab 2016b and beyond. For older versions use:
% U = P0 + [t.*u(1) ; t.*u(2)];
% V = Q0 + [t.*v(1) ; t.*v(2)];

d = pdist2(U',V');  % Pairwise distance between two sets of observations

[min_dist , position] = min2(d);

% Plot problem and result
figure
plot([P0(1) , P0(1)+u(1)] , [P0(2) , P0(1)+u(2)] , 'r-')
hold on;  axis equal;
plot([Q0(1) , Q0(1)+v(1)] , [Q0(2) , Q0(2)+v(2)] , 'g-')
plot([U(1,position(1)) , V(1,position(2))] , [U(2,position(1)) V(2,position(2))] , 'b-')
title(['Minimal distance: ' num2str(min_dist) '. t=' num2str(t(position(1))) '. s = ' num2str(t(position(2)))])
legend('Vector 1' , 'Vector 2' , 'Shortest distance')