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개)

Stephen23
Stephen23 2019년 2월 14일
편집: Stephen23 2019년 2월 14일

1 개 추천

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).
Jeff Miller
Jeff Miller 2019년 2월 13일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Circuits and Systems에 대해 자세히 알아보기

태그

질문:

2019년 2월 13일

편집:

2019년 2월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by