本帖最后由 吴鹏 于 2013-8-5 17:56 编辑
clear
a = rand(10,10,100000);
b = rand(10,10,100000);
tic
[m,n,p] = size(a);
l = size(b,2);
[i,j] = ndgrid(1:m,1:n);
i = bsxfun(@plus,i(:),0:m:p*m-1);
j = bsxfun(@plus,j(:),0:n:p*n-1);
u = reshape(permute(b,[2 1 3]),l,[])*sparse(j,i,a(:),m*p,n*p);
u = permute(reshape(u,l,m,[]),[2 1 3]);
toc
tic
for i = size(b,2):-1:1
d(:,i,:) = sum(bsxfun(@times,a,permute(b(:,i,:),[2 1 3])),2);
end
toc
tic;C = multiply3d(a,b);toc
tic
for i = size(a,3):-1:1
C(:,:,i) = a(:,:,i)*b(:,:,i);
end
toc
Elapsed time is 1.599254 seconds.
Elapsed time is 1.032681 seconds.
Elapsed time is 0.890517 seconds.
Elapsed time is 0.616669 seconds.
对于3*3的:
clear
a = rand(3,3,1000000);
b = rand(3,3,1000000);
tic
[m,n,p] = size(a);
l = size(b,2);
[i,j] = ndgrid(1:m,1:n);
i = bsxfun(@plus,i(:),0:m:p*m-1);
j = bsxfun(@plus,j(:),0:n:p*n-1);
u = reshape(permute(b,[2 1 3]),l,[])*sparse(j,i,a(:),m*p,n*p);
u = permute(reshape(u,l,m,[]),[2 1 3]);
toc
tic
for i = size(b,2):-1:1
d(:,i,:) = sum(bsxfun(@times,a,permute(b(:,i,:),[2 1 3])),2);
end
toc
tic;C = multiply3d(a,b);toc
tic
for i = size(a,3):-1:1
C(:,:,i) = a(:,:,i)*b(:,:,i);
end
toc
Elapsed time is 1.112965 seconds.
Elapsed time is 0.713329 seconds.
Elapsed time is 0.813784 seconds.
Elapsed time is 4.067793 seconds.
这是我机子上的测试结果。multiply3d是我们自己写的函数,算是一个折中。你写的这个 sum(bsxfun(@times,a,permute(b(:,i,:),[2 1 3])),2);也算折中,适合尺寸小的。尺寸大了后,纯循环就可以了。