Tricks to increase computational speed for D = (A + A*B).*C

1 Ansicht (letzte 30 Tage)
Arun S
Arun S am 19 Jun. 2024
Kommentiert: Arun S am 19 Jun. 2024
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!

Akzeptierte Antwort

Animesh
Animesh am 19 Jun. 2024
To optimize the computation of the large matrix sizes and the sparsity of MAT, you should consider the following approaches:
  1. 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.
  2. Precompute Static Values: If exp(-k*dt) does not change over iterations, compute it once before the loop and reuse the result.
  3. 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.
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

Weitere Antworten (0)

Kategorien

Mehr zu Mathematics finden Sie in Help Center und File Exchange

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by