首页 > 解决方案 > MATLAB中的最大似然解码

问题描述

X给定一个size的矩阵和一个size(5,3)的向量,我需要计算向量到所有向量的欧几里得距离并返回最小值。y(1,3)yX

例如

X =

    0.1338    0.0346    0.2961
    0.5320    0.4681    0.6784
    0.4484    0.5954    0.2847
    0.1437    0.5310    0.3946
    0.2854    0.0793    0.8621

y = 0.4484    0.5954    0.2847

所以在这种情况下,最小欧几里得距离y是矩阵中的第 3 行,X因为它是相同的。

我制作的代码如下:

X = rand(5,3)                %The matrix x 
y = rand(1,3)                %The vector y

[~, size_y] = size(y)        %size of y
[size_x, ~] = size(X)        %size of matrix x 

min_distance = zeros(size_x,size_y);   %Initialize the minimal distance 

 %% Calculate minimum distance square of vector y to every vector in x

   for i = 1 : size_y
        min_distance(:,i) = sum(abs(repmat(y(:,i),1,size_x) - X).^2,2); 
end 

min_distance_1 = min_distance;
[index, ~] = (min(min_distance_1,[],1)); 

results = index - 1; 

该代码的结果是不匹配错误,但是应该显示矩阵X中与向量具有最小欧几里得距离的行的索引!!y

代码有错误吗?或者我该怎么做?

标签: matlab

解决方案


我认为您的代码中缺少一些内容。对于欧几里得距离,某处应该有根。index 也是第二个返回值,而不是第一个返回值,并且没有理由 -1 和 matlab 中的索引。

有一个内置函数可以计算欧几里得距离,称为norm(). 对于您想要计算到每个向量的距离的情况,有一个非常vecnorm()适合的特殊情况。

differences = X-y 
%you dont need repmat but keep it if it helps your understanding of the code

distances = vecnorm(differences,2,2) 
%the first 2 is for 2-norm, which is Euclidean distance
%the second 2 for row-wise calculation

[~,index]= min(distances)

推荐阅读