MATLAB: Parallel Matrix row operation

MATLABmatrixparallelsparsity

Hi, I have a function which project a matrix to the matrix space with row sum equal to 1 and constrained by a sparsity structure. Here is the code
function [out] = Proj_DoubleStochasticM_reloc(Y)
global sparsity
Y = full(Y);
ii = [];
jj = [];
ss = [];
for i=1:length(sparsity)
ii = [ii;ones(size(sparsity{i}))*i];
jj = [jj;sparsity{i}];
ss = [ss Y(i,sparsity{i}) - (sum(Y(i,sparsity{i}))-1)/length(sparsity{i})];
end
[n,m] = size(Y);
out = sparse(ii, jj', ss', n,m);
So basically, the input is sparse. After I transform it to full, then a do a for loop on each row. The operation in each row is
Y(i,sparsity{i}) - (sum(Y(i,sparsity{i}))-1)/length(sparsity{i})
e.g
input = [1 2 3 4 5]
sparisty = [1 2]
then output is [1-(1+2-1)/2, 2-1-(1+2-1)/2, 0, 0, 0]
I was wondering whether there are any parallel approaches to do it, or direct methods on sparse matrix. Currently the most expensive line is last one, and full(), namely, transform sparsity; second is the for loop.
Thank you very much:)

Best Answer

function out = Proj_DoubleStochasticM_reloc(Y,sparsity)
[m,n]=size(Y);
[I,J]=deal(sparsity);
for k=1:length(sparsity)
I{k}(:)=k;
end
I=cell2mat(I); J=cell2mat(J);
bw=sparse(I,J,true,m,n);
Y=Y.*bw;
out=Y-bw.*(sum(Y,2)-1)./sum(bw,2); %EDITED
end