簡體   English   中英

使用arrayfun在Matlab中更快地進行for循環?

[英]Making a for-loop in Matlab faster by using arrayfun?

目前我有以下部分代碼:

for i = 2:N-1
  res(i) = k(i)/m(i)*x(i-1) -(c(i)+c(i+1))/m(i)*x(N+i) +e(i+1)/m(i)*x(i+1);
end

其中變量k,m,c和e是大小為N的向量,x是大小為2 * N的向量。 使用像arrayfun這樣的東西有沒有辦法更快地做到這一點!? 我無法弄清楚這一點:(我特別想通過以后在GPU上運行來加快速度,因此,arrayfun也會有所幫助,因為matlab不支持並行化for循環而且我不想買夾克包...非常感謝!

您不必使用arrayfun。 如果使用使用一些智能索引,它的工作原理:

    clear all

    N=20;
    k=rand(N,1);
    m=rand(N,1);
    c=rand(N,1);
    e=rand(N,1);
    x=rand(2*N,1);

    % for-based implementation
    %Watch out, you are not filling the first element of forres!
    forres=zeros(N-1,1); %Initialize array first to gain some speed.
    for i = 2:N-1
      forres(i) = k(i)/m(i)*x(i-1) -(c(i)+c(i+1))/m(i)*x(N+i) +e(i+1)/m(i)*x(i+1);
    end

    %vectorized implementation
    parres=k(2:N-1)./m(2:N-1).*x(1:N-2) -(c(2:N-1)+c(3:N))./m(2:N-1).*x(N+2:2*N-1) +e(3:N)./m(2:N-1).*x(3:N);

    %compare results; strip the first element from forres
    difference=forres(2:end)-parres %#ok<NOPTS>

首先,MATLAB通過PARFOR支持並行循環。 但是,由於計算量與您正在讀取和寫入的數據量相比較小,因此加速此類計算的可能性不大。

要重構GPUArray“ arrayfun ”的內容,您需要使循環體中的所有數組引用引用循環迭代,並使循環遍及整個范圍。 您應該能夠通過偏移某些數組並使用虛擬值填充來實現此目的。 例如,您可以在前面添加所有數組NaN ,並將x(i-1)替換為新變量x_1 = [x(2:N) NaN]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM