Loose question, on function handles / speeding up run times.
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
This is quite a loose question but I was very surprised to find this out so thought I would ask.
I was running a script where I defined a function handle call it g, which was acctaully very simple (basically a linear function). Insdie the scrip I called a function which took as one of its inputs the function handle g, and applied it to a fixed vector of length 200. My code was taking ages to run and everytime I paused the code I found it was computing the function handle of the vector. I decided to apply g to the vector and enter this value as the input to my function (instead of the handle g itself), now my code runs much much faster... I dont really get why this is happening, is this obvious?
2 commentaires
Jan
le 4 Nov 2021
Please post a minimal working example which reproduces your observation. It is not likely, that the readers can reproduce your code exactly based on the description. Then an explanation of the effect might consern something different.
Matt J
le 4 Nov 2021
It is not likely, that the readers can reproduce your code exactly based on the description.
Indeed, the following test seems to refute the claim.
A=rand(3000);
g=@(x) A*x(:);
x=rand(3000,1);
tic;
ver1(x,g);
toc
tic
ver2(g(x));
toc
function out=ver1(x,g)
out=g(x)+5;
end
function out=ver2(y)
out=y+5;
end
Réponses (1)
Aneela
le 20 Fév 2024
Hi Daniel Adams,
- The function “ver1” takes a vector “x” and a function handle “g”. When “ver1” is called, “g(x)” is computed, which is equivalent to matrix vector multiplication (A*x). Then 5 is added to each element of the resulting vector. The function handle “g” is called only once in this case.
- In “ver2”, you are pre-computing “g(x)” outside the function and then passing the result directly to “ver2”. Then, 5 is added to each element of the input vector “y”.
The execution time in both the cases are nearly identical, and the overhead of calling the function handle "g" is negligible in this context.
In scenarios where function handles involve more complex operations or where they are used inside loops with non-vectorized code, you might see a more noticeable difference in performance.
For further details on “Vectorization”, refer to the following link.
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements 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!