在MATLAB中矢量化代码

时间:2016-05-13 15:56:49

标签: performance matlab vectorization

如何在MATLAB中对此代码进行矢量化? 如果可能,我希望矩阵B是一个稀疏矩阵。

%% Y is a matrix l*n
%% X is a matrix k*n
B = [];
for i=1:l
    for j=1:n
        temp1 = zeros(1,n*l);
        temp1((i-1)*n+j) = -1;
        temp2 = zeros(1,l*k);
        temp2((i-1)*k+1:i*k) = (-Y(i,j)).*(X(:,j)');
        B = [B;[temp1,temp2]];
    end
end

我不知道如何对此代码进行矢量化,请帮忙!谢谢!

1 个答案:

答案 0 :(得分:0)

利用bsxfun进行元素乘法的遮蔽和矢量化计算,这是一个矢量化方法 -

%// Create left part of the output that is basically an identity matrix
parte1 = -eye(n*l);

%// Setup right part of output
parte2 = zeros(n*l,l*k);

%// Mask to set elements from the calculations of (-Y(i,j)).*(X(:,j)')
M = bsxfun(@eq,reshape(repmat(1:l,n,1),[],1),reshape(repmat(1:l,k,1),1,[]));
%// OR concisely : M = kron(eye(l),ones(n,k))==1

%// Perform vectorized calculations of (-Y(i,j)).*(X(:,j)') and set those
%// into second part at masked places
parte2(M) = -bsxfun(@times,permute(X,[2,1,3]),permute(Y,[2,3,1]));

%// Finally concatenate those parts for final output
out = [parte1,parte2];