Loose question, on function handles / speeding up run times.

3 views (last 30 days)
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 Comments
Jan
Jan on 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
Matt J on 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
Elapsed time is 0.005904 seconds.
tic
ver2(g(x));
toc
Elapsed time is 0.005773 seconds.
function out=ver1(x,g)
out=g(x)+5;
end
function out=ver2(y)
out=y+5;
end

Sign in to comment.

Answers (1)

Aneela
Aneela on 20 Feb 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!