Passing data through fminsearch
32 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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
0 个评论
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).
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!