Passing class method to fminunc

4 次查看(过去 30 天)
Anton Oskirko
Anton Oskirko 2022-8-23
回答: Raag 2025-3-11
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.

回答(1 个)

Raag
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:

类别

Help CenterFile Exchange 中查找有关 Nonlinear Optimization 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by