possible solution to speed up with power function?

3 次查看(过去 30 天)
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.

回答(1 个)

Deepak
Deepak 2024-8-5
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

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by