在 Matlab 中检查点的接近度
Check Proximity of Point in Matlab
我有数组 A。如何对其进行编码,以便将第 1 行与第 2 行、第 2 行与第 3 行以及第 3 行与第 4 行进行比较。如果欧几里德距离小于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
请提出更正建议。
您发布的代码中存在几个错误:
- 在
for
语句中缺少初始值
- 终止也应在
size(A,1)-1
结束
- `if' 语句中缺少一些括号
-
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
。
您可以通过在 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
我有数组 A。如何对其进行编码,以便将第 1 行与第 2 行、第 2 行与第 3 行以及第 3 行与第 4 行进行比较。如果欧几里德距离小于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
请提出更正建议。
您发布的代码中存在几个错误:
- 在
for
语句中缺少初始值 - 终止也应在
size(A,1)-1
结束
- `if' 语句中缺少一些括号
-
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
。
您可以通过在 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