计算如x1 = [1, 2, 3, 4, 5]和x2 = [6, 7, 8, 9, 10]之间的欧氏距离。代码如下:
% input same dimension vector
function distance = vecDis(x,y)
v_length = length(x);
d = 0;
for i = 1:1:v_length
z(i) = (x(i) - y(i))^2;
d = d + z(i);
end
distance = sqrt(d);
测试一下,对比代码:
x3 = [1 0 0 0 1 1];
x4 = [2 1 0 2 2 1];
d34 = (x3 - x4).^2;
d = sqrt(sum(d34(:)));
d = 2.6458;
vecDis(x3,x4)
2.6458
哈哈,测试通过,方便多了,但只能输入相同维度的向量。
网友评论