Parallel Matrix row operation

1 view (last 30 days)
Rui Xiang
Rui Xiang on 21 May 2019
Commented: Matt J on 22 May 2019
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:)

Accepted Answer

Matt J
Matt J on 21 May 2019
Edited: Matt J on 22 May 2019
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
  2 Comments
Rui Xiang
Rui Xiang on 22 May 2019
Thanks very much! It worked perfectly!
Matt J
Matt J on 22 May 2019
I think I had a mistake. I think the last line should be
out=Y-bw.*(sum(Y,2)-1)./sum(bw,2);

Sign in to comment.

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!