Pass values to a function when using fminunc

조회 수: 8 (최근 30일)
Christopher H
Christopher H 2016년 1월 21일
편집: Christopher H 2016년 1월 21일
I am trying to call fminunc in a script file on a function defined in another file. The problem is that I want to give parameters to this function (e.g. 'y' and 'dt'), although it is a function of x.
So I have in my myfunc.m something like this:
function [f df] = myfunc(y,dt)
f = @(x) (x - y)^2 / (2 * dt);
if nargout>1
df = @(x) ((x - y) / dt);
end
end
Then in my other script file, I have something like this:
dt = 0.1;
options = optimset('GradObj','on');
for i = 1:n
y = randn;
result = fminunc(myfunc(y,dt), 0, options);
end
The function 'res' is a function of x, but I want to be able to give it values that change as the for-loop is iterated through, and I am not quite sure how to do that. Any help would be appreciated.

채택된 답변

John D'Errico
John D'Errico 2016년 1월 21일
편집: John D'Errico 2016년 1월 21일
Learn to use function handles. (Properly.) And learn what the optimizers expect for arguments.
function [f df] = res(x,y,dt)
f = (x - y)^2 / (2 * dt);
if nargout>1
df = ((x - y) / dt);
end
...
result = fminunc(@(x) res(x,y,dt), 0, options);
A bit of a boring objective function.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Solver-Based Nonlinear Optimization에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by