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

3 views (last 30 days)
daniel adams
daniel adams on 4 Nov 2021
Commented: Matt J on 4 Nov 2021
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
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 (0)

Community Treasure Hunt

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

Start Hunting!