possible solution to speed up with power function?

4 vues (au cours des 30 derniers jours)
le duy nguyen
le duy nguyen le 10 Mar 2019
Réponse apportée : Deepak le 5 Août 2024
Is there any solution to speed up this code? The power function is too expensive. Any help is much appreciated.
tic
N = 1000000;
Linput = 500;
t = 1:Linput;
mTT = rand(N,1);
alf = rand(N,1);
beta = mTT./alf;
faktor = 1./(beta.^alf.*gamma(alf));
A = t.^(alf-1);
B = -t./beta ;
C = faktor.*A.*exp(B);
toc
Elapsed time is 104.574729 seconds.

Réponses (1)

Deepak
Deepak le 5 Août 2024
Hi Le Duy Nguyen,
To my understanding, you want to speed up the code provided by you that includes mathematical operations.
To optimize the code, Element wise operations such as divide, multiply, power can be performed by using the inbuilt method “bsxfun” of MATLAB.
“bsxfun” performs element-wise operations to two arrays, in optimized manner.
Also, we can precompute the “gamma(alf)” values to use them to calculate the “factor” which will speed up the process.
Attaching the documentation of “bsxfun” for reference – https://www.mathworks.com/help/matlab/ref/bsxfun.html
Here is the updated code snippet –
tic
N = 1000000;
Linput = 500;
t = 1:Linput;
mTT = rand(N,1);
alf = rand(N,1);
beta = mTT ./ alf;
gamma_alf = gamma(alf);
factor = 1 ./ (beta.^alf .* gamma_alf);
A = bsxfun(@power, t, alf-1);
B = -bsxfun(@rdivide, t, beta);
C = bsxfun(@times, factor, A) .* exp(B);
toc

Catégories

En savoir plus sur Mathematics dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by