【发布时间】:2010-10-15 17:54:07
【问题描述】:
我正在编写一个程序,我需要删除存储在矩阵中的重复点。问题是,当检查这些点是否在矩阵中时,虽然它们存在,但MATLAB无法识别它们。
在以下代码中,intersections函数获取交点:
[points(:,1), points(:,2)] = intersections(...
obj.modifiedVGVertices(1,:), obj.modifiedVGVertices(2,:), ...
[vertex1(1) vertex2(1)], [vertex1(2) vertex2(2)]);
结果:
>> points
points =
12.0000 15.0000
33.0000 24.0000
33.0000 24.0000
>> vertex1
vertex1 =
12
15
>> vertex2
vertex2 =
33
24
应从结果中消除两点(vertex1 和 vertex2)。应该通过以下命令完成:
points = points((points(:,1) ~= vertex1(1)) | (points(:,2) ~= vertex1(2)), :);
points = points((points(:,1) ~= vertex2(1)) | (points(:,2) ~= vertex2(2)), :);
这样做之后,我们得到了这个意想不到的结果:
>> points
points =
33.0000 24.0000
结果应该是一个空矩阵。如您所见,第一对(或第二对?)[33.0000 24.0000] 已被淘汰,但第二对没有。
然后我检查了这两个表达式:
>> points(1) ~= vertex2(1)
ans =
0
>> points(2) ~= vertex2(2)
ans =
1 % <-- It means 24.0000 is not equal to 24.0000?
有什么问题?
更令人惊讶的是,我制作了一个只有以下命令的新脚本:
points = [12.0000 15.0000
33.0000 24.0000
33.0000 24.0000];
vertex1 = [12 ; 15];
vertex2 = [33 ; 24];
points = points((points(:,1) ~= vertex1(1)) | (points(:,2) ~= vertex1(2)), :);
points = points((points(:,1) ~= vertex2(1)) | (points(:,2) ~= vertex2(2)), :);
结果如预期:
>> points
points =
Empty matrix: 0-by-2
【问题讨论】:
-
这也已解决here
-
@Kamran:对不起,当您在其他问题中询问比较值时,我没有指出浮点比较的危险。我没有立即想到你可能会遇到这个问题。
-
附带说明,比较
1.2 - 0.2 - 1 == 0和1.2 - 1 - 0.2 == 0。令人惊讶,不是吗?处理浮点数时,运算顺序很重要。 -
@Tick Tock:作为问题的作者,我什至无法理解您为我的问题选择的标题。它也没有反映出当您打印出变量时,MATLAB 没有显示数字的整个浮点部分。
-
@m7913d,我明白了。但通常他们会在较新的问题上贴上“重复”标签。请阅读重复标签规则:meta.stackexchange.com/questions/10841/…
标签: matlab floating-point precision