matlab 三维矩阵向量化,三维矩阵对应页数矩阵相乘的向量化(不用循环语...

本帖最后由 吴鹏 于 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);也算折中,适合尺寸小的。尺寸大了后,纯循环就可以了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值