Info
Cette question est clôturée. Rouvrir pour modifier ou répondre.
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?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Philip Borghesani
le 25 Fév 2016
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 commentaire
Cette question est clôturée.
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!