Parallel Matrix row operation

1 次查看(过去 30 天)
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:)

采纳的回答

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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by