MATLAB: Do I receive an error about the recursion limit while using an ODE solver or an Optimization Toolbox function

fminsearchfsolvefzeroodeode45optimizationOptimization Toolbox

When I run the following simple program to optimize a function:
function y=MyMinimize(x)
y=x(1)^2+x(2)^2;
z=fminsearch(@MyMinimize,[1000 1000]);
I used the following function call:
MyMinimize([1 1])
However, this did not work. I received the following error:
??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available stack space can crash MATLAB and/or your computer.

Best Answer

This error occurs because you are calling the optimization or ODE solver function inside the function which you are trying to optimize or solve. This creates a recursive loop, which will cause MATLAB to display an error.
Take the call to the optimization or ODE solver function out of your function and call it from the command line. You can solve the example above using:
z=fminsearch(@(x) x(1)^2+x(2)^2,[1000 1000]);
If you are using a version of MATLAB prior to MATLAB 7.0 (R14), you will need to define the function to be integrated as an inline function or a function file. For example, use the function "MyMinimize.m":
function y=MyMinimize(x)
y=x(1)^2+x(2)^2;
and this command from the command line to optimize the function:
z=fminsearch(@MyMinimize,[1000 1000]);