fminsearch for multivariable function in matlab

To use the fminsearch function in MATLAB for minimizing a multi-variable function, you need to define an anonymous function that takes the input variables and returns the value to be minimized.

Here's an example of how to use fminsearch with a 2-variable function:

main.m
% Define the function to be minimized
fun = @(x) x(1)^2 + x(2)^2;

% Set the initial guess for the minimizing values
x0 = [1, 2];

% Use fminsearch to find the minimizing values
x = fminsearch(fun, x0);
203 chars
9 lines

In this example, fun takes a 2-element array x as input and returns the sum of the squared elements. x0 is the initial guess for the minimizing values. fminsearch then returns an array x with the minimizing values.

You can replace the definition of fun with your own function that takes your desired input variables and returns the value to be minimized.

Note that fminsearch only finds local minima, so it may be necessary to try different initial guesses to find the global minimum. Also, fminsearch assumes that the function is continuous and differentiable, so it may not work for functions with discontinuities or sharp corners.

gistlibby LogSnag