Classifying sparse matrix in parfor loop
조회 수: 5 (최근 30일)
이전 댓글 표시
Dear all,
The following for-loop is defined:
iend = nz - 1;
jend = nr - 1;
for i = 1 : iend
for j = 1 : jend
k = i * Nr + j;
dz = z_grid(i+1) - z_grid(i);
dr = r_grid(j+1) - r_grid(j);
A_sol(k,k) = - dz * (r_grid(j+1) * a(i+1,j+1) + r_grid(j) * b(i+1,j)) - dr * r_grid(j+1) * (c(i+1,j+1) + d(i,j+1));
end
end
with z_grid and r_grid being vectors and a, b, c and d matrices. The loop takes long to compute and I would like to use parloop to speed up the process.
From MATLAB Help I know that the code should be written in the form of:
iend = nz - 1;
jend = nr - 1;
for i = 1 : iend
for j = 1 : jend
k(j) = i * Nr + j;
dr = r_grid(j+1) - r_grid(j);
end
dz = z_grid(i+1) - z_grid(i);
A_sol(k,k) = -dz* (r_grid(j+1) * a(i+1,j+1) + r_grid(j) * b(i+1,j)) - dr * r_grid(j+1) * (c(i+1,j+1) + d(i,j+1));
end
And write A_sol(k,k) in the form A_sol(k,:). However, the rows and columns have the same indexation, and I cannot come up with a solution to still make this work. Could someone help me out?
Thank you in advance,
WIth kind regards,
Bjorn
댓글 수: 1
Matt J
2021년 11월 11일
Shouldn't k be given by,
k = (i-1) * Nr + j;
As you have it now, k will not start at k=1, but instead it will run from Nr+1 to iend*Nr+jend.
채택된 답변
Matt J
2021년 11월 11일
편집: Matt J
2021년 11월 11일
The loop takes long to compute and I would like to use parloop to speed up the process.
I doubt it will, but the loop can be further optimized by pre-computing some things. Also, it will be much faster if A_sol is computed using the sparse() command.
r_grid=r_grid(:).'; %make sure these are row vectors
z_grid=z_grid(:).';
DZ=[0,diff(z_grid)].';
DR=[0,diff(r_grid)];
Term1=(-DZ .* a - DR .* c ).*r_grid;
Term2=(-DZ .* b).*r_grid;
Term3=(-DR .* d).*r_grid;
N=length(A_sol);
A_diag=zeros(N,1);
iend = nz - 1;
jend = nr - 1;
for i = 1 : iend
for j = 1 : jend
k = i * Nr + j;
A_diag(k) = Term1(i+1,j+1) +Term2(i+1,j) + Term3(i,j+1);
end
end
A_sol=spdiags(A_diag(:),0,N,N);
댓글 수: 2
Matt J
2021년 11월 13일
Glad it helped but 2^10 is pretty small. You could probably make things faster just by using a non-sparse matrix.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!