Matlab代码优化和删除循环 [英] Matlab code optimization and removing loops

查看:207
本文介绍了Matlab代码优化和删除循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人可以帮助我优化这段代码,我不能独自删除此循环-欢迎.

I can't remove this loops by myself, if anybody can help me with optimization this piece of code - welcome.

M = length(w);
expt = exp(-t .* (phis * w'));
G = zeros(M, M);
for i = 1 : M
    for j = 1 : M
        last = 2 * reg_coef * eye(M);
        G(i,j) = last(i, j) + mean(expt .* t .^2 .* phis(:,i) .* phis(:,j) ./ (1 + expt) .^ 2);
    end
end

  • w -大小为(1xM)
  • phis -大小为(NxM)
  • t -大小为(Nx1)
    • w - size is (1xM)
    • phis - size is (NxM)
    • t - size is (Nx1)
    • 推荐答案

      通过编写简洁的代码,您可以做得更好-确保分配正确,确保从循环等中删除重复的计算.

      You can do alot better by just writing cleaner code - ensure that you allocate properly, ensure that you remove duplicate calculations from loops etc:

      您还可以看到生成的矩阵G是对称的,因此通过仅计算上三角形并随后将其作为转置填充下三角形,即可立即获得2x加速.

      You can also see that the resulting matrix G is symmetric, so you get an immediate 2x speed-up by only calculating the upper triangle and filling in the lower triangle afterwards as a transpose.

      至少对于我的MATLAB,通过使用临时数组将对mean()的调用向量化,可以实现另一个大大的加速.

      At least with my MATLAB another big speed-up is achieved by vectorising the call to mean() through the use of a temporary array.

      N = 100;
      M = 100;
      
      w = rand(1,M);
      t = rand(N,1);
      phis = rand(N,M);
      reg_coeff = rand(1,1);
      
      expt = exp(-t .* (phis * w'));
      
      %% Initial version
      tic
      for i = 1 : M
         for j = 1 : M
            last = 2 * reg_coeff * eye(M,M);
            G1(i,j) = last(i,j) + mean(expt .* t .^ 2 .* phis(:,i) .* phis(:,j) ./ (1 + expt) .^ 2);
         end
      end
      t1 = toc;
      
      %% Faster version
      tic
      coeff = expt .* t .^ 2 ./ (1 + expt) .^ 2;
      G2 = zeros(M,M);
      TT = zeros(M,M);
      for i = 1 : M
         for j = i : M % only form upper triangle
            TT(:,j) = coeff .* phis(:,i) .* phis(:,j);
         end
         G2(i,i:M) = mean(TT(:,i:M),1); % vectorise call to mean()
      end
      G2 = 2 * reg_coeff * eye(M,M) + G2 + triu(G2,+1)';
      t2 = toc;
      
      %% Compare versions
      speed = t1/t2
      error = max(max(abs(G2 - G1)))
      

      对于这种100x100情况,我的机器上的加速速度约为41.0.

      For this 100x100 case the speed-up was around 41.0 on my machine.

      希望这会有所帮助.

      这篇关于Matlab代码优化和删除循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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