我的代码需要帮助。该代码用于查找平方距离问题的最小值。我通过示例提供代码,我相信这将是解释我需要的最简单方法。
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的参数估计问题中使用该代码。
第一种情况:向量矩阵情况
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句