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