- Use Sparse Matrices: If you haven't already, convert MAT to a sparse matrix format in MATLAB using sparse(MAT). This will significantly speed up matrix-vector multiplications for large, sparse matrices.
- Precompute Static Values: If exp(-k*dt) does not change over iterations, compute it once before the loop and reuse the result.
- Avoid Growing Arrays in a Loop: Preallocate the full size of g before the loop to avoid dynamically resizing it during each iteration, which is costly.
Tricks to increase computational speed for D = (A + A*B).*C
1 次查看(过去 30 天)
显示 更早的评论
Hello
I am working on computing the time evolution of a distribution. The distribution evolves as follows
g(t + dt) = (g(t) + dt*MAT*g(t)).*exp(-k*dt)
here g and k are column vector of size m*1, MAT is a square matrix of size m*m.
Say i have to evolve it "n" times, the way I have attempted my solution is
g = zeros(m,n)
g(:,1) = g0 % initalising
MAT, k = something pre calculated
for i = 1:1:n
g(:,i+1) = (g(:,i) + dt*MAT*g(:,i) ).*exp(-k*dt)
end
This is the conventional basic way I guess but it takes a long time. How else can I implement the evolution to make it faster.
For perspective the matrices are of the order of 10,000*10,000 and I would like to evolve it for another 5000 ish points
MAT is a mostly a sparse matrix. It has significant non zero diagonal elements and in a given row maybe 50-60 elements are non zero.
Grateful for any suggestions!
0 个评论
采纳的回答
Animesh
2024-6-19
To optimize the computation of the large matrix sizes and the sparsity of MAT, you should consider the following approaches:
Given these points, your revised code snippet would look something like this:
% Assuming MAT is already defined and is sparse
% Convert MAT to sparse format if not already
% MAT = sparse(MAT); % Uncomment if MAT is not already sparse
% Precompute constants
exp_neg_kdt = exp(-k*dt);
% Preallocate g
g = zeros(m, n+1);
g(:,1) = g0; % Initial condition
% Time evolution loop
for i = 1:n
g(:,i+1) = (g(:,i) + dt*MAT*g(:,i)) .* exp_neg_kdt;
end
I hope this helps!
Animesh
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!