如何加速for循环

时间:2016-10-13 06:07:44

标签: matlab for-loop optimization vectorization

以下代码用于计算矩阵的一阶导数和Hesse。我在计算中使用了很多for循环,但速度并不令人满意。我正在寻找一种方法来加快循环速度。

具体来说,我们定义f(U,V)=||X-UV||_{F}^{2},其中X \in \mathbb{R}^{N \time D}U \in \mathbb{R}^{N \time K}V \in \mathbb{R}^{K \time D}。我想得到d^2f(U_{0},V_{0}),它也被称为Hesse矩阵。

实际上,您无需仔细查看代码。我只想展示它的样子。问题出在for循环上。它们太多了,导致计算速度慢。

是否有比使用for循环更好的解决方案?

n y=f__(U,V,X,H,W)% U \in N*K, V\in K*D, X \in N*D, H \in D*K
Dim0=size(X);
Dim1=size(U);
N=Dim0(1);%N is the row number of X
D=Dim0(2);%D is the column number of X
K=Dim1(2);%K is the column number of U
% Set Up Matrix Size Parameters
A=zeros(N*K+K*D);

% The diagnal part of H
for k=1:N
    for l=1:K
        %A((k-1)*K+l,(k-1)*K+l)=0;
        for j=1:D
            A((k-1)*K+l,(k-1)*K+l)=A((k-1)*K+l,(k-1)*K+l)+2+2*V(l,j)^2*W(k,j)^2;
        end
    end
end

% The non-diagnal part of H
for k=1:N
    for l=1:K
        for n=1:K
            if(l==n)
                continue;
            end
            %A((k-1)*K+l,(k-1)*K+n)=0;
            for j=1:D
                A((k-1)*K+l,(k-1)*K+n)=A((k-1)*K+l,(k-1)*K+n)+2*V(n,j)*V(l,j)*W(k,j)^2;
            end
        end
    end
end

%The diagnal and non-diagnal part of V
for k=1:K
    for l=1:D
        for m=1:K
            %A(N*K+(k-1)*D+l,N*K+(m-1)*D+l)=0;
            for i=1:N
                A(N*K+(k-1)*D+l,N*K+(m-1)*D+l)=A(N*K+(k-1)*D+l,N*K+(m-1)*D+l)+2*U(i,k)*U(i,m)*W(i,l)^2;
            end
        end
    end
end

%The part of H and V
for k=1:K
    for l=1:D
        for m=1:N
            for n=1:K
                %A(N*K+(k-1)*D+l,(m-1)*K+n)=0;
                if(n==k)
                    A(N*K+(k-1)*D+l,(m-1)*K+n)=(2*V(n,l)*U(m,k)+2*(U(m,:)*V(:,l)-X(m,l)))*W(m,l)^2;
                else
                    A(N*K+(k-1)*D+l,(m-1)*K+n)=2*V(n,l)*U(m,k)*W(m,l)^2;
                end
            end
        end
    end
end

%This is a symmatric matrix
for i=N*K+1:N*K+K*D
    for j=1:N*K
        A(i,j)=A(j,i);
    end
end

y=A;

0 个答案:

没有答案