Vectorized operation of sparse matrix

조회 수: 3 (최근 30일)
Esegboria Osarhemen
Esegboria Osarhemen 2019년 3월 5일
댓글: Esegboria Osarhemen 2019년 3월 6일
I have the following code
a = randi(903,10293,1800);
c = cell(1,10293);
for n = 1:10293
b = a(n,:);
i = b(1:length(b)-1);
j = b(2:length(b));
k = ones(1,length(b)-1);
s = sparse(i,j,k,903,903);
total = nansum(s,2);
p = s./total;
c{n} = p;
end
After it runs for sometime, matlab runs out of memory. Without the """ total = nansum(s,2); p = s./total; """ part, and setting c{n} =s, it runs fine. Can anyone tell me how to fix this and make the code run efficiently?

채택된 답변

Matt J
Matt J 2019년 3월 5일
편집: Matt J 2019년 3월 5일
The problem is that you have lots of 0/0 operations occuring whenever total=0. These result in lots of NaNs in p rendering it highly non-sparse. I don't know how you wish to define the results of 0/0 in this situation, but here is one possibility for avoiding them:
a = randi(903,10293,1800);
c = cell(1,10293);
for n = 1:10293
b = a(n,:);
i = b(1:length(b)-1);
j = b(2:length(b));
k = ones(1,length(b)-1);
s = sparse(i,j,k,903,903);
total = nansum(s,2);
total(~total)=1; %<---Matt J inserted
p=s./total;
c{n} = p;
end
  댓글 수: 1
Esegboria Osarhemen
Esegboria Osarhemen 2019년 3월 6일
Thank you very much, it works now, just how i wanted

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by