Passing class method to fminunc
조회 수: 4 (최근 30일)
이전 댓글 표시
Hello, comrades!
I've ran into a problem: when I use fminunc(), it requires the first argument to be the handle of the investigated function. Everything was fine, when I made separate .m-file with my function. However, the project has grown up since that time, and now this function is a method of a class, and I need to pass it to fminunc (it is situated in another method, see sample code)
classdef MyProblem < handle
properties
N
...
end
methods
<other methods>
function f = F(obj, par)
<function body>
%%% par is a 1 x obj.N array of numbers
%%% this method returns one number
end
function [x,fval,exitflag,output,grad,hessian] = optim_fminunc(obj, x0)
%% This is an auto generated MATLAB file from Optimization Tool.
%% Start with the default options
options = optimoptions('fminunc');
%% Modify options setting
%% Here I modify options for the optimization
[x,fval,exitflag,output,grad,hessian] = ...
fminunc(@(x) F(obj, x),x0,options);
end
end
end
end
Here I get an error "Dot indexing is not supported for variables of this type."
Is it even possible to optimize function F from such a class? What should I do if it is so?
Thank you in advance!
P.S. If my code is not ok, and it is strongly recommended to place here a sample that could be ran, let me know.
댓글 수: 0
답변 (1개)
Raag
2025년 3월 11일
Hi Anton,
To resolve the error, you need to update the function handle so that the method is bound to the object instance. Instead of writing:
fminunc(@(x) F(obj, x), x0, options);
resolve
fminunc(@(x) obj.F(x), x0, options);
Here is a code that illustrates the change in context:
classdef MyProblem < handle
properties
N % Number of variables
end
methods
% Constructor to set the number of variables
function obj = MyProblem(N)
obj.N = N;
end
% Objective function (for example, the sum of squares)
function f = F(obj, x)
f = sum(x.^2);
end
% Optimization method using fminunc
function [x, fval] = runOptimization(obj, x0)
options = optimoptions('fminunc', 'Display', 'iter');
% Bind the function handle to the object using dot notation
[x, fval] = fminunc(@(x) obj.F(x), x0, options);
end
end
end
By using ‘@(x) obj.F(x)’, MATLAB correctly recognizes ‘F’ as a method of ‘obj’, which avoids the "Dot indexing is not supported" error.
For a better understanding of the above solution, refer to the following MATLAB documentation:
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Nonlinear Optimization에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!