2016-05-13 87 views
2

如何在MATLAB中矢量化这段代码? 如果可能,我希望矩阵B是一个稀疏矩阵。在MATLAB中向量化代码

%% 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 

我不知道如何矢量化这段代码,请大家帮忙!谢谢!

+0

要创建一个矩阵,是'L * N *(N * L + 1 * K) '元素很长......那是你打算做什么的? – gariepy

+0

我想解决一个线性规划问题。表示线性约束的矩阵“B”。 –

+0

@ZAlex公布的解决方案是否适合您? – Divakar

回答

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]; 
+0

非常感谢 –

+0

@Zlex所以,它工作还是有内存问题? – Divakar

+0

我不知道...因为内存限制超过... –