【问题标题】:Saving values in a vector inside a loop, and finding the specific loop at which a certain element is saved将值保存在循环内的向量中,并找到保存某个元素的特定循环
【发布时间】:2018-07-25 00:43:44
【问题描述】:

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

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

提前致谢! /阿里安

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

% 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

【问题讨论】:

  • 只保存最小值和位置不是更高效吗?
  • 请提供一个可运行的示例(即确保所有变量都已定义),或者至少提供一些具有代表性的输入和输出。另请参阅:minimal reproducible example。你的代码有什么问题?此外,是什么让您如此确定嵌套循环是这里的最佳方法(......也许它可以使用矢量化来解决)?最好确保您询问的是问题而不是解决方案。另请参阅:XY Problem.
  • 现在提供了整个代码并对其进行了一些更改,似乎可以解决问题

标签: matlab loops for-loop indexing location


【解决方案1】:

您不需要嵌套循环,这要归功于 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')

【讨论】:

  • Emm,不错的见解,但您的代码似乎有一些错字。 t 是 1x101 向量,u 是 2x1,所以我们无法运行 t.*u
  • 它在 Matlab 2016b 中工作。他们在这个版本中改变了数组操作。更多信息here。在旧版本中,您可以使用 U = P0 + [t.*u(1) ; t.*u(2)];
  • 感谢您的回答 :) 效果很好
猜你喜欢
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
相关资源
最近更新 更多