MATLAB矢量化的成对距离
我正在努力化一个函数,该函数在两个矢量x = 2xn和v = 2xm之间执行一些成对的差异,对于某个任意n,M。我在n = 1时可以工作功能适用于具有n个任意的输入。
实际上,我希望此功能要做的是x的每一列找到x(:,列)(A 2x1)和V(A 2xm)之间的范围差异。
类似的帖子是 this ,尽管我无法推广它。
当前实施
function mat = vecDiff(x,v)
diffVec = bsxfun(@minus, x, v);
mat = diffVec ./ vecnorm(diffVec);
示例
x =
1
1
v =
1 3 5
2 4 6
----
vecDiff(x,v) =
0 -0.5547 -0.6247
-1.0000 -0.8321 -0.7809
I'm struggling to vectorise a function which performs a somewhat pairwise difference between two vectors x = 2xN and v = 2xM, for some arbitrary N, M. I have this to work when N = 1, although, I would like to vectorise this function to apply to inputs with N arbitrary.
Indeed, what I want this function to do is for each column of x find the normed difference between x(:,column) (a 2x1) and v (a 2xM).
A similar post is this, although I haven't been able to generalise it.
Current implementation
function mat = vecDiff(x,v)
diffVec = bsxfun(@minus, x, v);
mat = diffVec ./ vecnorm(diffVec);
Example
x =
1
1
v =
1 3 5
2 4 6
----
vecDiff(x,v) =
0 -0.5547 -0.6247
-1.0000 -0.8321 -0.7809
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的方法可以如下适合您的需求:
x
或v
的尺寸,以便其列数变为 third>第三 dimension。我在下面的代码中选择v
。bsxfun
)to计算A
是2
×M
×n
差异数组,其中m
和n
nx
和v
的列数。如果您希望按其他顺序输出尺寸,则可能需要以不同的方式应用
PERTER
。Your approach can be adapted as follows to suit your needs:
x
orv
so that its number of columns becomes the third dimension. I'm choosingv
in the code below.bsxfun
) to compute a2
×M
×N
array of differences, whereM
andN
are the numbers of columns ofx
andv
.You may need to apply
permute
differently if you want the dimensions of the output in another order.假设您的两个输入矩阵是A(A 2 X N矩阵)和B(A 2 X M矩阵),其中每列代表不同的观察值(请注意,这不是表示数据的传统方式)。
请注意,输出的大小为n x m x 2。
out = zeros(n,m,2);
我们可以使用内置函数
pdist2
找到它们之间的距离。dists = pdist2(a。',b。');
(矩阵的方向所需的换位)才能获得单个x和y距离,我想到的最简单的方法就是使用repmat:
然后,我们可以通过前面找到的距离进行归一化:
这返回矩阵
out
,其中位置的元素(i,j,:)
是a(:,i)
和b(:j)之间的规范距离。
Suppose your two input matrices are A (a 2 x N matrix) and B (a 2 x M matrix), where each column represents a different observation (note that this is not the traditional way to represent data).
Note that the output will be of the size N x M x 2.
out = zeros(N, M, 2);
We can find the distance between them using the builtin function
pdist2
.dists = pdist2(A.', B.');
(with the transpositions required for the orientation of the matrices)To get the individual x and y distances, the easiest way I can think of is using repmat:
And we can then normalise this by the distances found earlier:
This returns a matrix
out
where the elements at position(i, j, :)
are the components of the normed distance betweenA(:,i)
andB(:,j)
.