Passing data through fminsearch
30 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (2)
Jeff Miller
am 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
0 Kommentare
Stephen23
am 14 Feb. 2019
Bearbeitet: Stephen23
am 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).
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!