Delooping variables that are loop-dependent

1 visualizzazione (ultimi 30 giorni)
Jack
Jack il 22 Set 2023
Risposto: Vatsal il 4 Ott 2023
I have some code that I am looking to considerably speed up.
I'm using A to 'normalise' B which then alters A through some propagator C. D then converts the vector A into a single number that is the signal. Everything outside of the loop can be treated as a constant.
Unlike the previous question I asked, B0 and C are now no longer constants and are dependent on n, so I am unable to pull out the matrix power from the loop.
The expm line is considerably the slowest, followed by the mldivide line.
Any help would be much appreciated.
% Constants w.rt. n
A = rand(16,1);
idx = [1 6 11 16];
D = rand(1,16);
N = 1e5;
signal = zeros(N,1);
tic
for n = 1:N
% Constants dependent on n
B0_ = rand(16,1);
C_ = rand(16,16);
C = expm(C_*1e-6);
B0 = -C\B0_;
Aidx = A(idx);
Asum = sum(Aidx);
B = B0*Asum;
A = B + C*(A-B);
signal(n) = D*A;
end
toc
Elapsed time is 3.467775 seconds.

Risposte (1)

Vatsal
Vatsal il 4 Ott 2023
Hi @Jack,
I understand that you are looking to optimize the code. In the given code variable “A” normalise “B” which then alters “A” through some propagator “C”. Afterwards, "D" converts the vector "A" into a single number representing the signal. To improve the code's performance, I have implemented an alternative approach for matrix exponentiation. Instead of using the "expm" function, I utilized the Taylor series method to calculate the matrix exponentiation. This modification has yielded better results compared to using the "expm" function
I have also included the modified code below, which incorporates the Taylor series method for matrix exponentiation:
A = rand(16,1);
idx = [1 6 11 16];
D = rand(1,16);
N = 1e5;
signal = zeros(N,1);
tic
for n = 1:N
% Constants dependent on n
B0_ = rand(16,1);
C_ = rand(16,16);
X=C_*1e-6;
E = zeros(size(X));
F = eye(size(X));
k = 1;
while norm(E+F-E,1) > 0
E = E + F;
F = X*F/k;
k = k+1;
end
C = E;
B0 = -C\B0_;
Aidx = A(idx);
Asum = sum(Aidx);
B = B0*Asum;
A = B + C*(A-B);
signal(n) = D*A;
end
toc
For more information and different methods for matrix exponentiation, you can refer to the following link:
I hope this helps!

Categorie

Scopri di più su Mathematics and Optimization in Help Center e File Exchange

Prodotti


Release

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by