matlab - MATLAB中的最大似然解码
问题描述
X
给定一个size的矩阵和一个size(5,3)
的向量,我需要计算向量到所有向量的欧几里得距离并返回最小值。y
(1,3)
y
X
例如
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
代码有错误吗?或者我该怎么做?
解决方案
我认为您的代码中缺少一些内容。对于欧几里得距离,某处应该有根。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)
推荐阅读
- javascript - 运行“pm2 start server --watch”而不是“pm2 start server”时出现 CORS 错误。不存在“Access-Control-Allow-Origin”标头
- heroku - Heroku:无法使用元掩码登录到我的托管应用程序
- java - Java 信号量,acquire() 和 release()
- sip - Opensips 2.4 无法拨打电话
- android - 使用 Firebase Google Analytics SDK 构建 Unity 项目失败:“无法加载文件或程序集 'UnityEditor.iOS.Extensions.Xcode”
- python - 所有组合可能性
- php - 从帐户内容中删除 WooCommerce 消息
- python - Qtimer 并在 15 秒后关闭应用程序
- docker - 连接到网络失败,请确保您的网络选项正确并检查管理器日志:超出上下文期限
- r - 根据循环中当前数据帧的子集创建新的重命名数据帧