I wrote 2 snippets as below, they both try to find minimum value, but one repetitively uses function handles and the other uses a sub function. It turns out the speed are very different? Why?
Info
This question is closed. Reopen it to edit or answer.
Show older comments
Two snippets are as follow (they are not my original codes and are used for illustration only), the input y is just an array, for example, you can run method1(rand(500,1)) and method2(rand(500,1)), respectively. Interestingly, although both do the same job, when y is very large, method1 would take unbearable long time but method2 works pretty fine. What makes this huge difference?
Code 1
function out=method1(y)
f=@(x)0;F=@(x)0;
for i=1:length(y)
f=@(x)x(1)*f(x)^2+x(2)*y(i)^2;
F=@(x)x(1)*F(x)+x(2)*log(f(x)^2+1)-10*y(i)^3;
end
options=optimoptions(@fminunc,'Algorithm','quasi-newton');
out=fminunc(F,[0,0],options);
end
Code 2
function out=method2(y)
options=optimoptions(@fminunc,'Algorithm','quasi-newton');
out=fminunc(@(x)subfun(x,y),[0,0],options);
end
function F=subfun(x,y)
f=0;F=0;
for i=1:length(y)
f=x(1)*f^2+x(2)*y(i)^2;
F=x(1)*F+x(2)*log(f^2+1)-10*y(i)^3;
end
end
4 Comments
Image Analyst
on 25 Feb 2016
Why would you just redefine two anonymous functions over and over again in a loop? That's just crazy. Makes no sense. You never even use f, and F would just end up leaving the loop with the last form that you assign to it in the very last iteration.
jgg
on 25 Feb 2016
It seems like the speed difference is mainly because you're defining and redefining 2*length(y) anonymous functions then evaluating them. Have you tried using profile then profile viewer to see which parts are slow? I'll bet it's this issue.
I agree with Image Analyst though, the algorithm makes absolutely no sense in the first place, though.
Shawn Miller
on 25 Feb 2016
Edited: Shawn Miller
on 25 Feb 2016
Shawn Miller
on 25 Feb 2016
Edited: Shawn Miller
on 25 Feb 2016
Answers (1)
Philip Borghesani
on 25 Feb 2016
0 votes
Profile your code, think about what the code is doing. Method2 makes one function call to subfun per iteration. Method1 makes many thousands of function calls using the many anonymous functions you have created per iteration. There is no comparison in the amount of work being done. Recursive solutions are rarely the most efficient solution to a problem.
I do find that Method1 runs significantly faster in R2015b then in previous versions but it is still much slower then Method2.
1 Comment
Shawn Miller
on 26 Feb 2016
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!