Passing data through fminsearch

25 views (last 30 days)
Cameron Birchall
Cameron Birchall on 13 Feb 2019
Edited: Stephen23 on 14 Feb 2019
I want to use fminsearch to fit parameters to a model. I'm not sure, however, the best method to pass data through fminsolve. Currently I'm passing data through as a global variable although I have previously been advised to avoid defining globals whenever possible. For a minimal working example I minimize the residual sum of squares to find the mean below. Any comments on why I should not use a global variable and what I can do instead.
Thanks, Cameron
% Estimate mean by minimizing residual sum of squares through fminsolve
% Define data global
global y
% generate one hundred draws of mean 100 alongside a standard normal error term
y = 100 + randn(100,1) ;
% initial parameter guess
par_0 = [0] ;
% Define fminsolve
[par_hat , rss] = fminsearch(@min_rss, par_0) ;
% Residual sum of squares function
function rss = min_rss(par)
global y
rss = [y - par]'*[y - par] ;
end

Answers (2)

Jeff Miller
Jeff Miller on 13 Feb 2019
One way is to nest the rss function:
function [ par_hat , rss ] = finder
% A wrapper function to avoid globals
y = 100 + randn(100,1) ;
% initial parameter guess
par_0 = [0] ;
% Define fminsolve
[par_hat , rss] = fminsearch(@min_rss, par_0) ;
% Residual sum of squares function
function rss = min_rss(par)
rss = [y - par]'*[y - par] ;
end
end

Stephen23
Stephen23 on 14 Feb 2019
Edited: Stephen23 on 14 Feb 2019
You should definitely avoid global variables.
For your situation the easiest way to parameterize a function is to use a simple anonymous function:
% generate one hundred draws of mean 100 alongside a standard normal error term:
y = 100 + randn(100,1);
% Call fminsolve:
fun = @(v) min_rss(v,y); % anonymous function
[par_hat, rss] = fminsearch(fun, 0)
% Residual sum of squares function:
function rss = min_rss(par,y)
rss = (y - par)' * (y - par);
end
Giving:
par_hat =
100.1231
rss =
133.7660
Note that I also replaced your square brackets in the function with the correct grouping operator (parentheses), exactly as the MATLAB Editor recommended (you should always pay attention to the warnings shown by the editor).

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!