Saving values in a vector inside a loop, and finding the specific loop at which a certain element is saved
    3 visualizaciones (últimos 30 días)
  
       Mostrar comentarios más antiguos
    
    Arian Abedin
 el 14 de Feb. de 2018
  
    
    
    
    
    Editada: Arian Abedin
 el 14 de Feb. de 2018
            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
 h=0.01;
  mindist=[];
  for t=0:h:1
      for s=0:h:1
          if F==0 
              s=0;
              t=e/c;
              mindist=[mindist; norm((P0+s*u)-(Q0+t*v))];
          else
              mindist=[mindist; norm((P0+s*u)-(Q0+t*v))];
          end
      end
  end
  [mindist,loc]=min(mindist);
  mindist
0 comentarios
Respuesta aceptada
  Birdman
      
      
 el 14 de Feb. de 2018
        Try this(don't forget to define e, c , u , v etc):
   h=0.01;
   t=0:h:1;
   s=zeros(1,numel(t));
   mindist=[];
    for i=1:numel(t)
        for j=1:numel(s)
            if F==0 
                t(i)=e/c;
                mindist(i,j)=[mindist; norm((P0+s(j)*u)-(Q0+t(i)*v))];
            else
                mindist(i,j)=[mindist; norm((P0+s(j)*u)-(Q0+t(i)*v))];
            end
        end
    end
    [mindist,loc]=min(mindist);
    mindist
1 comentario
  Arian Abedin
 el 14 de Feb. de 2018
				
      Editada: Arian Abedin
 el 14 de Feb. de 2018
  
			
		Más respuestas (1)
  Jos (10584)
      
      
 el 14 de Feb. de 2018
        A few thoughts:
- There is a potential problem in your code as you set the loopcounters s and t to a value within the loop.
 - F does not change within the loop, so the if can be taken out of the loop
 
The easiest way given your current code: store the values of i and s alongside the output of norm, so mindist will be a N-by-3 vector
    ...
        mindist = [mindist ; norm(...) s t]
    ...
    [~, loc]=min(mindist(:,1)) ;
    mindist = mindist(loc) % three values
However, as you do not provide any information about the variables P0, Q0, e, c, u and v, the whole algorithm might be written much more efficiently! For instance by pre-allocating the output and use an index counter into the possible values of s:
srange = 0:h:1 ;
mindist = zeros(numel(srange),1) ;
for s_k = 1:numel(srange)
    s_value_to_use = srange(s_k) ;
    mindist(s_k,:) = ...
end
1 comentario
Ver también
Categorías
				Más información sobre MATLAB Coder en Help Center y File Exchange.
			
	Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!