2
votes

How to vectorize this code in MATLAB? If possible, I wish matrix B to be a sparse matrix.

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

I don't know how to vectorize this code, please help! Thanks!

1
you are creating a matrix that is l*n*(n*l + l*k) elements long...is that what you intended to do? - gariepy
I want to solve a Linear Programming. Matrix B representing linear constraints. - Z Alex
@ZAlex Did the posted solution work for you? - Divakar
Unfortunately,out of memory...n=87856, l = 208, k=14...Maybe sparse Matrix is necessary... - Z Alex

1 Answers

0
votes

Making use of bsxfun for masking and vectorized calculations of the elementwise multiplications, here's a vectorized approach -

%// 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];