Passing data through fminsearch

30 ビュー (過去 30 日間)
Cameron Birchall
Cameron Birchall 2019 年 2 月 13 日
編集済み: Stephen23 2019 年 2 月 14 日
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

回答 (2 件)

Jeff Miller
Jeff Miller 2019 年 2 月 13 日
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 2019 年 2 月 14 日
編集済み: Stephen23 2019 年 2 月 14 日
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).

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by