【问题标题】:optimizing nested for loop in matlab在matlab中优化嵌套for循环
【发布时间】:2013-11-07 21:50:37
【问题描述】:

我正在尝试优化我的代码的性能(例如速度)。我是矢量化的新手,并尝试自己矢量化,但没有成功(也尝试 bxsfun、parfor、某种矢量化等)。谁能帮我优化这段代码,以及如何做到这一点的简短描述?

% for simplify, create dummy data
Z = rand(250,1)
z1 = rand(100,100)
z2 = rand(100,100)

%update missing param on the last updated, thanks @Bas Swinckels and @Daniel R
j = 2;
n = length(Z);
h = 0.4;


tic
[K1, K2] = size(z1);
result = zeros(K1,K2);

for l = 1 : K1
    for m = 1: K2
        result(l,m) = sum(K_h(h, z1(l,m), Z(j+1:n)).*K_h(h, z2(l,m), Z(1:n-j)));    
    end
end

result = result ./ (n-j);
toc

K_h.m 函数是边界核,定义为(x 是标量,y 可以是向量)

function res = K_h(h, x,y)
 res = 0;

 if ( x >= 0 & x < h)
    denominator = integral(@kernelFunc,-x./h,1);  
    res = 1./h.*kernelFunc((x-y)/h)/denominator;
 elseif (x>=h & x <= 1-h)
    res = 1./h*kernelFunc((x-y)/h);
 elseif (x > 1 - h & x <= 1)
    denominator = integral(@kernelFunc,-1,(1-x)./h);
    res = 1./h.*kernelFunc((x-y)/h)/denominator;
 else    
    fprintf('x is out of [0,1]');
    return;
 end
end

获取结果需要很长时间:\经过的时间为 13.616413 秒。

谢谢。欢迎任何cmets。 P/S: 对不起我的英语不好

【问题讨论】:

  • jn 是什么?常量?
  • h ?请使用clear all,然后尝试执行您的代码,您会注意到任何缺少的初始化。
  • 感谢@BasSwinckels。我刚刚更新了。对不起我的错误
  • 感谢@DanielR。我刚刚更新了

标签: matlab optimization vectorization


【解决方案1】:

一些观察:似乎Z(j+1:n))Z(1:n-j) 在循环内是恒定的,所以在循环之前进行索引操作。接下来,看起来循环真的很简单,每个result(l, m)都依赖于z1(l, m)z2(l, m)。这是使用arrayfun 的理想案例。解决方案可能看起来像这样(未经测试):

tic

% do constant stuff outside of the loop
Zhigh = Z(j+1:n);
Zlow = Z(1:n-j);

result = arrayfun(@(zz1, zz2) sum(K_h(h, zz1, Zhigh).*K_h(h, zz2, Zlow)), z1, z2)

result = result ./ (n-j);
toc

我不确定这是否会快很多,因为我猜运行时间不会由 for 循环控制,而是由 K_h 函数内完成的所有工作控制。

【讨论】:

  • 感谢您的快速回复。我试试这个,但这无助于提高速度
  • arrayfun 是一种很好的短代码技术,但在很多时候并不能提高性能:stackoverflow.com/questions/12522888/…
猜你喜欢
  • 2012-01-27
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多