有没有一种方法可以在MATLAB中加快串联速度? [英] Is there a way to speed up concatenation in MATLAB?

查看:80
本文介绍了有没有一种方法可以在MATLAB中加快串联速度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想沿着三维连接起来

z = cat(3,A,B,C);

很多次.如果我是在第二维上这样做的话,那么

Many many times. I if I was doing that along the second dimension then

z = [A,B,C];

会比

z = cat(2,A,B,C);

是否可以在三维空间上做类似的事情,还是有其他方法可以加快速度?

Can a similar thing be done along the third dimension or is there any other way to speed this up?

推荐答案

有些索引选项比cat(3,...)具有更好的性能.

There are some indexing options to get a slightly better performance than cat(3,...).

这两个解决方案都使用U(30,30,3)=0;而不是zeros(30,30,3)进行预分配,但未保存,因为当U已经是较大的变量时,这将导致下标尺寸不匹配.

Both solutions use U(30,30,3)=0; instead of zeros(30,30,3) to preallocate, but it is unsave as it will result in a subscript dimension missmatch when U is already a variable of a larger size.

第一个选项是分别分配不同的切片.

The first option is to assign the different slices individually.

%fast but unsafe preallocation
U(30,30,3)=0;
%robust alternative:
%U=zeros(30,30,3)
U(:,:,3)=C;
U(:,:,1)=A;
U(:,:,2)=B;

第二个选项是使用线性索引.对于z1 = cat(3,A,B,C);z2=[A;B;C],确实z1(:)==z2(:)

The second option is to use linear indexing. For z1 = cat(3,A,B,C); and z2=[A;B;C] it is true that z1(:)==z2(:)

%fast but unsafe preallocation
U(30,30,3)=0;
%robust alternative:
%U=zeros(30,30,3)
U(:)=[A,B,C];

我对解决方案进行了基准测试,并将其与cat(3,A,B,C)[A,B,C]进行了比较.线性索引解决方案仅比[A,B,C]慢一点.

I benchmarked the solutions, comparing it to cat(3,A,B,C) and [A,B,C]. The linear indexing solution is only slightly slower than [A,B,C].

0.392289 s for 2D CAT
0.476525 s for Assign slices
0.588346 s for cat(3...)
0.392703 s for linear indexing

基准测试代码:

N=30;
A=randn(N,N);
B=randn(N,N);
C=randn(N,N);
T=containers.Map;
cycles=10^5;
tic;
for i=1:cycles
    W=[A;B;C];
    X=W+1;
end
T('2D CAT')=toc;
tic;
for i=1:cycles
    W=cat(3,A,B,C);
    X=W+1;
end
T('cat(3...)')=toc;
U=zeros(N,N,3);
tic;
for i=1:cycles
    U(N,N,3)=0;
    U(:,:,3)=C;
    U(:,:,1)=A;
    U(:,:,2)=B;
    V=U+1;
end
T('Assign slices')=toc;
tic;
for i=1:cycles
    U(N,N,3)=0;
    U(:)=[A,B,C];
    V=U+1;
end
T('linear indexing')=toc;


for X=T.keys
    fprintf('%f s for %s\n',T(X{1}),X{1})
end

这篇关于有没有一种方法可以在MATLAB中加快串联速度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆