我试图找到一种最快的方法来查找数组中的唯一值,并删除 0
作为唯一值的可能性。
现在我有两个解决方案:
result1 = setxor(0, dataArray(1:end,1)); % This gives the correct solution
result2 = unique(dataArray(1:end,1)); % This solution is faster but doesn't give the same result as result1
dataArray
等同于:
dataArray = [0 0; 0 2; 0 4; 0 6; 1 0; 1 2; 1 4; 1 6; 2 0; 2 2; 2 4; 2 6]; % This is a small array, but in my case there are usually over 10 000 lines.
所以在这种情况下,result1
等于 [1; 2]
并且 result2
等于 [0; 1; 2]
。
unique
函数更快,但我不想考虑 0
。有没有一种方法可以使用 unique
来做到这一点,而不是将 0
视为唯一值?还有其他选择吗?
编辑
我想为各种解决方案计时。
clc
dataArray = floor(10*rand(10e3,10));
dataArray(mod(dataArray(:,1),3)==0)=0;
% Initial
tic
for ii = 1:10000
FCT1 = setxor(0, dataArray(:,1));
end
toc
% My solution
tic
for ii = 1:10000
FCT2 = unique(dataArray(dataArray(:,1)>0,1));
end
toc
% Pursuit solution
tic
for ii = 1:10000
FCT3 = unique(dataArray(:, 1));
FCT3(FCT3==0) = [];
end
toc
% Pursuit solution with chappjc comment
tic
for ii = 1:10000
FCT32 = unique(dataArray(:, 1));
FCT32 = FCT32(FCT32~=0);
end
toc
% chappjc solution
tic
for ii = 1:10000
FCT4 = setdiff(unique(dataArray(:,1)),0);
end
toc
% chappjc 2nd solution
tic
for ii = 1:10000
FCT5 = find(accumarray(dataArray(:,1)+1,1))-1;
FCT5 = FCT5(FCT5>0);
end
toc
结果:
Elapsed time is 5.153571 seconds. % FCT1 Initial
Elapsed time is 3.837637 seconds. % FCT2 My solution
Elapsed time is 3.464652 seconds. % FCT3 Pursuit solution
Elapsed time is 3.414338 seconds. % FCT32 Pursuit solution with chappjc comment
Elapsed time is 4.097164 seconds. % FCT4 chappjc solution
Elapsed time is 0.936623 seconds. % FCT5 chappjc 2nd solution
但是,sparse
和 accumarray
的解决方案仅适用于 integer
。这些解决方案不适用于 double
。
最佳答案
这是一个关于 accumarray
的古怪建议,使用 Floris 的测试数据进行了演示:
a = floor(10*rand(100000, 1)); a(mod(a,3)==0)=0;
result = find(accumarray(nonzeros(a(:,1))+1,1))-1;
感谢 Luis Mendo 指出使用 nonzeros
,没有必要执行 result = result(result>0)
!
请注意,此解决方案需要整数值数据(不一定是整数数据类型,但不包含小数部分)。比较浮点值是否相等(如 unique
所做的那样)是危险的。参见 here和 here .
原始建议:将unique
与setdiff
结合起来:
result = setdiff(unique(a(:,1)),0)
或者在unique
之后用逻辑索引删除:
result = unique(a(:,1));
result = result(result>0);
我通常不喜欢像 (result(result==0)=[];
) 那样分配 []
,因为它对于大型数据集来说效率很低。
在 unique
之后删除零应该更快,因为它对更少的数据进行操作(除非每个元素都是唯一的,或者如果 a
/dataArray
很短)。
关于arrays - 在数组中查找唯一值的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20667745/