我能给你的最快速度是4秒(在我的机器上).我不是百分百肯定你是否尝试过这个,但无论如何你都去了.
我有一个包含这些内容的m文件randbool.m,用于生成测试数据.
function x = randbool(m,n)
x = logical(rand(m,n) < 0.5);
生成用于测试的数据:
>> u = randbool(1,20000);
>> M = randbool(30,20000);
我可以想到三种循环M行的方法(使用bsxfun,使用repmat,使用循环)和两种方法来拉出你想要的元素(连接&或逐点乘法.*).最快的是bsxfun和连接的组合:
Bsxfun /连词
>> tic, for i=1:1000, bsxfun(@and,u,M); end, toc
Elapsed time is 4.068684 seconds.
Bsxfun /乘法
>> tic, for i=1:1000, bsxfun(@times,u,M); end, toc
Elapsed time is 4.856784 seconds.
Repmat /连词
>> tic, for i=1:1000, utmp=repmat(u,30,1); M&utmp; end, toc
Elapsed time is 7.305158 seconds.
Repmat / multiplication
>> tic, for i=1:1000, utmp=repmat(u,30,1); M.*utmp; end, toc
Elapsed time is 8.117164 seconds.
循环/连接
>> tic, for i=1:1000, for j = 1:30, out(j,:)=u&M(j,:); end; end, toc
Elapsed time is 7.110872 seconds.
循环/乘法
>> tic, for i=1:1000, for j = 1:30, out(j,:)=u.*M(j,:); end; end, toc
Elapsed time is 8.322888 seconds.