Incorrect results from intersect when entering imaginary numbers
2 次查看(过去 30 天)
显示 更早的评论
The attached file, data1.txt, contains the X-Y coordinates of the points in Set A.
The other file, data2.txt, contains the X-Y coordinates of the points in Set B.
My objective is to find the intersection of the two sets.
I used intersect() in MATLAB in three ways but got different answers.
First way, combining the X array and the Y array in the same set as table(X, Y) and then input the two tables to intersect();
Second way, combining the X array, Y array in the same set as X+1i.*Y and then input the two imaginary number arrays to intersect();
Third way, combining the X array, Y array in the same set as X+100.*Y and then input the two real number arrays to intersect().
I found the answers from the first two ways were wrong!
1 个评论
Dave B
2021-10-23
Can you expand on what you mean by the first two ways were wrong? From what I can tell all three methods produce the same result (other than how the values are sorted)...
load('data1.txt')
load('data2.txt')
% I think these are the three ways you used intersect:
t1=table(data1(:,1),data1(:,2));
t2=table(data2(:,1),data2(:,2));
res1=intersect(t1,t2);
res2=intersect(data1(:,1)+data1(:,2)*1i,data2(:,1)+data2(:,2)*1i);
res3=intersect(data1(:,1)+data1(:,2)*100,data2(:,1)+data2(:,2)*100);
% Here's an alternative that doesn't use intersect:
res_alt=data2(ismember(data2,data1(ismember(data1,data2,'rows'),:),'rows'),:);
% Are the the same number of elements?
height(res1)==height(res2)
height(res1)==height(res3)
height(res1)==height(res_alt)
% Decompose the complex back into real components and sort rows to compare with res1:
isequal(sortrows(table2array(res1)), sortrows([real(res2) imag(res2)]))
% Decompose the *100 out of res3
res3_y=(floor(res3/50)*50)/100;
res3_x=res3-res3_y*100;
a=sortrows(table2array(res1))-sortrows([res3_x res3_y]);
% some floating point error is to be expected, right?
max(abs(sort(res1.Var1)-sort(res3_x)))
max(abs(sort(res1.Var2)-sort(res3_y)))
% check res1 against res_alt
isequal(sortrows(table2array(res1)), sortrows(res_alt))
回答(2 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!