如何使用生成矩阵的3个循环对代码进行矢量化

时间:2017-07-12 14:16:40

标签: matlab performance for-loop multidimensional-array vectorization

你能否帮助我将这个Matlav代码矢量化为构建维A的矩阵MNx(2+N-1)xR以加速它?目前需要约。 8秒

正在初始化

R=200;
M=400;
N=20;
B=[kron((1:1:M)', ones(N,1)) repmat((1:1:N)', M,1)]; %(MN)x(2)

B看起来像

B=[1 1;
   1 2;
   ...;
   1 20;
   2 1;
   2 2;
   ...
   2 20;
   ...
   400 20]

CODE

A=[ repmat(B,1,1,R)  zeros(M*N,N-1,R)]; %Allocate the space
                                        %(MN)x(2+N-1)x(R)
                                        % I want A(:,1:2,r)=B for r=1,...,R


%Fill the remaining columns of A in the following way
for r=1:R
    utemp1=randn(M*N, N-1); %Generate a matrix of random 
                            %numbers of dimension (M*N)x(N-1)
    utemp2=randn(M, N);  %Generate a matrix of random 
                         %numbers of dimension (M)x(N)
    utemp3=zeros(M*N,N-1); %Generate a matrix of random 
                           %numbers of dimension(M)x(N-1)
    for m=1:M
        for j=1:N
            utemp3((m-1)*N+j,:)= utemp2(m,j)+[utemp2(m,1:j-1) utemp2(m,j+1:N)]; %(1)x(N-1)
              %e.g. if m=2, j=3, I want to fill the 23th row of utemp3
              %with utemp2(2,3)+[utemp2(2,1:2) utemp2(m,4:20)];

              %e.g. if m=4, j=1, I want to fill the 61st row of utemp3
              %with utemp2(4,1)+[utemp2(4,2:20)];
        end
    end
    A(:,3:end,r)=utemp1+utemp3;     %sum utemp1
end

一些解释

代表r=1,...,R

A就是这样

代表m=1,...,Mj=1,...,N

前两列中以A(:,:,r)开头的[m j]中的行填入剩余的(N-1)列,其中uj+uh+ujhh~=j,其中uj, uh, ujh {1}}是iid标准高斯数字,可以在utemp1utemp2中找到。

1 个答案:

答案 0 :(得分:1)

您可以预先计算索引并在500次迭代中使用它们:

idx = repmat(reshape(1:M*N,M,N).',1,N);
idx = reshape(idx(logical(kron(~eye(N),ones(1,M)))),N-1,[]).';
for k=1:500
    for r=1:R
        utemp2=randn(M*N,1);
        A(:,3:end,r)=randn(M*N, N-1)+bsxfun(@plus,utemp2,utemp2(idx) );
    end
end

然而,分配大型矩阵,特别是重复元素,以及对其进行矢量化操作并不总是最有效的方法。有内置函数直接在原始数组上运行,避免重复数组元素。