matlab中集合运算函数——解析

1. unique函数

 对于unique(A,'rows')而言, 速度较慢, 例: 

A = randi(10,1000,100000); %生成10以下数字的1000×100000的矩阵

 第一种方式: 

tic
[a1 b1 c1] = unique(A,'rows');
toc

       运行时间  t=2.656930s;

 第二种方式: 

tic
t = max(max(A));
B = zeros(size(A,1),1);
for i = 1:size(A,2)
    B = B*(t+1) + A(:,i);
end
[a2 b2 c2] = unique(B);
toc

       运行时间  t=0.369617s;

 运行时间上第二种方法比第一种减少了10倍, 且得到了相同的结果. 

2. union函数

  参照程序: 

A = randperm(8000000,7800000);
B = randperm(5000000,4300000);
%% 第一种方法
tic
C = union(A,B);
toc       %运行时间 t=1.360395s
%% 第二种方法
tic
b = zeros(1,max([A,B]));
b([A B]) = 1;
D = find(b);
toc       %运行时间 t=0.558845s

  可知第二种方式比使用函数运行时间更短. 

3. setdiff函数

  参照程序: 

A = randperm(8000000,7800000);
B = randperm(5000000,4300000);
%% 第一种方法
tic
C = setdiff(A,B);  %意义为 A-B
toc     %运行时间 t = 3.845448s
%% 第二种方法
tic
a = max(A);
b = zeros(1,a);
b(A) = 1;
b(B(find(B<(a+1)))) = 0;
D = find(b);
toc     %运行时间 t = 0.571202s

 可知第二种方式比使用函数运行时间更短

综上所述, Matlab中有关集合运算的函数并不一定运行快, 比如unique、union、setdiff、setxor、intersect、ismember等函数, 上述函数皆可以仿照本文方法重新编写加快程序运行速度. 并且, 程序短≠运行快

原文地址:https://www.cnblogs.com/common376/p/5824649.html