我有数组A.如何对第一行进行编码,将第一行与第二行,第二行,第三行和第三行进行比较。如果欧几里德距离小于1,则从数组A中省略,否则保留在其中。
A=[ 1.05, 33.43; 1.66, 30.81; 1.78, 30.98; 2.01, 28.05]
A=sortrows(A,[1,2])
for i=size(A,1)
if (sum(A(i,:)-A(i+1)).^2, 2)<1
A(i+1,:)=[ ]
end
end
请建议更正。
答案 0 :(得分:2)
您发布的代码中有几处错误:
for
语句中缺少initia值size(A,1)-1
square root
euclidean distance
可能的解决方案可能是:
A=[ 1.05, 33.43; 1.66, 30.81; 1.78, 30.98; 2.01, 28.05]
A=sortrows(A,[1,2])
% Make a copy of the original matrix
B=A
% Loop over the matrix rows
for i=1:size(A,1)-1
% Evaluate the Euclidean Distance and store it in an array (for verification purpose)
ed(i)=sqrt(sum((A(i,:)-A(i+1,:)).^2))
% If the Euclidean Distance is less than the threshold, delete the row in the
% B matrix
if(ed(i) < 1)
B(i+1,:)=[]
end
end
这给出了:
欧几里德距离
ed =
2.69007 0.20809 2.93901
原始矩阵
A =
1.0500 33.4300
1.6600 30.8100
1.7800 30.9800
2.0100 28.0500
更新了矩阵
B =
1.0500 33.4300
1.6600 30.8100
2.0100 28.0500
原始矩阵的第三行已删除,欧几里德距离等于0.20809
。
答案 1 :(得分:2)
您可以在A
:
A = [1.05, 33.43; 1.66, 30.81; 1.78, 30.98; 2.01, 28.05];
A = sortrows(A,[1 2]);
A1 = A(1:end-1,:);
A2 = A(2:end,:);
完成此操作后,欧几里德距离可以采用矢量化方式计算,通常比Matlab中的for
循环好得多:
D = sqrt(sum((A1 - A2) .^ 2,2));
% this is because the computation is performed on *rows-1*, hence the
% indexation must be adjusted in order to produce the correct result
D = [Inf; D];
最后,只保留距离大于或等于1
的点:
A(D >= 1,:)
ans =
1.0500 33.4300
1.6600 30.8100
2.0100 28.0500