Accelerate a loop involving the built-in integral command
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
A Matlab script has the following instructions:
for p = 1 : N
Output(2*p-1,1) = integral(@(t) cos((2*p-1)*t).*my_fun(t,param), 0, T);
Output(2*p,1) = integral(@(t) sin((2*p-1)*omega*t).*my_fun(t,param), 0, T);
end
Computing the function
my_fun(t,param)
for a given t is costly and the issue with the above loop is that the function
my_fun(t,param)
is called twice. Assuming that the quadrature points in the integral command are the same, calling the function twice is not efficient. Is there a remedy to this by keeping the structure of the proposed code?
1 Kommentar
John D'Errico
am 2 Jun. 2023
@pluton schmidt - I moved your answer to a comment. PLease use comments to make a comment.
Antworten (2)
Steven Lord
am 2 Jun. 2023
Assuming that params doesn't change, consider using the memoize function to create an object you can use in your integrand function to cache the inputs and corresponding outputs, so if you call the function multiple times with the same inputs it will use the cached results.
memSin = memoize(@sin);
results = zeros(1, 5);
for k = 1:5
results(k) = integral(@(x) memSin(x).^k, 0, pi);
memSin.stats.Cache % Show cache usage
end
results
Note that each time after the first, the number of TotalMisses (inputs that weren't already cached) didn't change while the HitCount (the number of inputs that were already cached) increased.
2 Kommentare
Torsten
am 2 Jun. 2023
Bearbeitet: Torsten
am 2 Jun. 2023
You will have to reorder the "Output" array, but I think the code should be faster.
my_fun = @(t,param) t.^2;
T = 2;
omega = 5;
N = 2;
param = 2;
fun = @(t) [cos((2*(1:N)-1).*t),sin((2*(1:N)-1).*omega.*t)].*my_fun(t,param);
Output = integral(fun,0,T,'ArrayValued',true)
3 Kommentare
Torsten
am 2 Jun. 2023
Bearbeitet: Torsten
am 2 Jun. 2023
Very interesting indeed, both for the parallelization and the fact that my_fun does not have to be computed twice.
Twice ? It only has to be computed once instead of 2*N times. If you don't see a gain in computation time, your function cannot be that time-consuming as you think it is.
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!