2014-05-08 19 views
1

我需要我的代码帮助。该代码用于查找平方距离问题的minumin。我通过一个例子提供我的代码,我相信这将是解释我需要的最简单的方法。找到组合矩阵的索引位置

clear all 
clc 
x=10.8; % is a fixed value 
y=34; % is a fixed value 
z=12; % is a fixed value 
A = [11 14 1; 5 8 18; 10 8 19; 13 20 16]; % a (4x3) matrix 
B = [2 3 10; 6 15 16; 7 3 15; 14 14 19]; % a (4x3) matrix 

我创造它在这下面的方式组成一个新的矩阵C

C1 = bsxfun(@minus, A(:,1)',B(:,1)); 
C1=C1(:); % this is the first column of the new matrix C 
C2 = bsxfun(@minus, A(:,2)',B(:,2)); 
C2=C2(:); % this is the second column of the new matrix C 
C3 = bsxfun(@minus, A(:,3)',B(:,3)); 
C3=C3(:); % this is the third column of the new matrix C 
C = [C1 C2 C3]; % the new matrix C of size (16x3) 

C有以这种方式形成!这就是我的意思,当我在我的标题组成的矩阵中写道

然后:

[d,p] = min((C(:,1)-x).^2 + (C(:,2)-y).^2 + (C(:,3)-z).^2); 
d = sqrt(d); 
outputs: 
d = 18.0289; 
p = 13; 

让我满足该分钟问题的距离(d)和位置(P) 。

我的问题: 我需要找到其中的A and B组合给了我这个p值,换句话说,我需要从'A,B'这给了我这个最佳C1,C2,C3指数:

C1 = bsxfun(@minus, A(?,1)',B(?,1)); 
C2 = bsxfun(@minus, A(?,2)',B(?,2)); 
C3 = bsxfun(@minus, A(?,3)',B(?,3)); 

?是索引位置我需要,在这种情况下,矩阵A的索引位置和B.

的我有以下说明的索引位置手工计算值:

我知道:

C = [9 11 -9 
5 -1 -15 
4 11 -14 
-3  0 -18 
3  5  8 
-1 -7  2 
-2  5  3 
-9 -6 -1 
8  5  9 
4 -7  3 
3  5  4 
-4 -6  0 
11 17  6 
7  5  0 
6 17  1 
-1  6 -3] 

我知道,我的最佳指数在第13位给出。该指数位置追溯到:

[13-2 20-3 16-10] 

这是A(4,:) - B(1,:)

我需要一个代码,它可以帮助我找到从A这个指标和B提前

谢谢!

PS。我正在使用ODE的参数估计问题中的代码。

+0

这令人困惑,从标量和矢量之间的距离开始。一个向量没有一个位置,只有一个量级和一个方向。你的意思是你想找到1点和存储在矢量中的一组点之间的最短距离?然后你谈论矩阵'A'和'B'。鉴于点和矢量之间距离的某种定义,很难理解'A'和'B'代表什么。第三,您应该在示例代码中修复'z'中的错误。 – patrik

回答

1

第一种情况:向量矩阵情况下

subvals = bsxfun(@minus,A,[x y z]) 
[distance,index] = min(sqrt(sum(subvals.^2,2))) 

第二种情况:两个矩阵的情况下

subvals = bsxfun(@minus,A,permute(B,[3 2 1])); 
[distances,indices] = min(sqrt(sum(subvals.^2,2)),[],3) 

测试对于第二种情况:

%%// Get some random data into A and B 
A = randi(20,8,3) 
B = randi(20,4,3) 

%%// Just to test out out code for correctness, 
%%// let us make any one one row of B, say 3rd row equal to 
%%// any one row of A, say the 6th row - 
B(3,:) = A(6,:) 

%%// Use the earlier code 
subvals = bsxfun(@minus,A,permute(B,[3 2 1])); 
[distances,indices] = min(sqrt(sum(subvals.^2,2)),[],3) 

%%// Get the minimum row index for A and B 
[~,min_rowA] = min(distances) 
min_rowB = indices(min_rowA) 

验证

min_rowA = 
    6 

min_rowB = 
    3 

编辑1响应张贴在的问题简单的例子]:

标题说,你有兴趣在寻找两个矩阵的差异,然后找到它之间的最短距离到矢量[xyz]。所以,我希望这是你所需要的 -

x=10.8; 
y=34; 
z=12; 
A = [11 14 1; 5 8 18; 10 8 19; 13 20 16]; 
B = [2 3 10; 6 15 16; 7 3 15; 14 14 19]; 

C = A -B; %%// Distance of two vectors as posted in title 
subvals = bsxfun(@minus,C,[x y z]) 
[distance,index] = min(sqrt(sum(subvals.^2,2))) 

输出

distance = 
    31.0780 

index = 
    3 

编辑2:当你这样做之后 -

[d,p] = min((C(:,1)-x).^2 + (C(:,2)-y).^2 + (C(:,3)-z).^2); 

如果你正在寻找找到A和B的相应指标,你可以这样做 -

[minindex_alongB,minindex_alongA] = ind2sub(size(A),p)