我正在尝试找到一种最快的方法来查找数组中的唯一值,并将 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
不起作用。
dataArray
时间而不是更多的迭代次数。但只是为了好玩,加入FCT3 = FCT3(FCT3~=0);
,因为这通常比分配[]
更快。 - chappjcrand(10e3,10)
一次性处理所有10列。 - chappjcunique
函数,浮点数也会带来一些挑战。请参见此处和此处。请考虑是否可以使用整数值索引而不是浮点数值进行操作。 - chappjc