How to pass functions in MATLAB function fminsearch

## Keywords

Matlab, fminsearch, anonymous functions

## Review Status

Reviewed 2010-06-03.

# Overview

The Matlab function fminsearch uses Nelder-Mead direct search to find the minimum of an unconstrained multivariate function. We demonstrate how to use the function through a trivial example: computing the mean of a sample of random variates. See to the Matlab Help for additional examples and a full description of the function; see any decent textbook on numerical optimisation for a description of Nelder-Mead direct search.

# The Problem

Suppose we have a function to be minimised. It accepts an input $u$ and returns a scalar $b$, the objective function evaluated at $u$. But generally, such a function will take several arguments, not just $u$. The question is: how to pass the function to fminsearch?

# Solution

A trivial example: the mean of a sample $y=y_1, y_2,\ldots$ is the number $u$ which minimises the following expression

(1)
\begin{align} \sum (y_i - u)^2\,. \end{align}

## Matlab

Equation (1) as a Matlab function:

function b = objfunc(u,y)
residuals = y-u;
b = sum(residuals.^2);
end


This function needs to be saved as an m-file. (In this simple case, we could have written it inline.) This objective function takes two arguments: a candidate solution $u$, and data $y$. The ‘trick’ is to create an anonymous function that fixes the data ($y$), and only allows one argument ($u$) to be changed.

Here is the call to fminsearch:

% generate 100 random numbers drawn from the normal distribution
y = randn(100,1);
mean(y) % the value we should eventually get

% assign an inital guess for the solution
u0 = 10;

%Here is the call to the fminserach.
%@(u) is the anonymous handle for the objfunction.
%This function is then passed to fminsearch.

sol = fminsearch(@(u) objfunc(u, y), u0)