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

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

Arian
1#
Arian Published in 2018-02-14 12:29:16Z
 I have a code that calculates the minimum distance between two line segments by discretizing t, and s between 0 and 1 with h. The code saves the distance for each value of s and t in a vector and the smallest value is picked out at the end. I would like to find the corresponding t and s for which the minimum distance occurs. For example, if the minimum distance is located at index 3000 in the 'mindist' vector, which value of t and s does this correspond? Thanks in advance! /Arian Edit: I provided the entire code with some comments aswell. I've changed it a bit and this seems to do the trick: % 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))  minval = 1.0710 
Zep
2#
 you do not need nested cycles, thanks to Matlab's pdist2() function. Here is an example: 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')