找到组合矩阵的索引位置

时间:2014-05-08 09:26:37

标签: arrays matlab matrix indexing minimum

我的代码需要帮助。该代码用于查找平方距离问题的 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;

给我满足 min 问题的距离(d)和位置(p)。

我的问题: 我需要找到A and B的哪些组合给出了我的p值,换句话说我需要来自'A,B'的索引,这给了我最优 {{ 1}}:

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的索引位置。

手工计算我有以下插图:

我知道:

?

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

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-2 20-3 16-10]

我需要一个代码,可以帮助我从A和B中找到这些索引

提前致谢!

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

1 个答案:

答案 0 :(得分: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 [对发布的简单示例的回复]:

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

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)