define an objective function with user defined number of variables in fminunc()

5 ビュー (過去 30 日間)
Shikun Nie
Shikun Nie 2025 年 1 月 17 日
編集済み: Matt J 2025 年 1 月 17 日
Suppose I want to define the following function in matlab which returns the output of fminunc(). The problem here is the number of variables depends on the user input. How do I define the objective function fun() such that it automatically adapts to the number of variables.
function xmin = problem(n)
if n == 1
fun = @(x) x^2+2*x+3;
xmin = fminunc(fun,1);
end
if n == 2
fun = @(x) x(1)^2+x(2)^2+2*(x(1)+x(2))+3;
xmin = fminunc(fun,[1 0]);
end
if n == 3
fun = @(x) x(1)^2+x(2)^2+x(3)^2+2*(x(1)+x(2)+x(3))+3;
xmin = fminunc(fun,[1 0 0]);
end
% n is the number of variables for fun.
% the list goes on. n==4, n==5,...
end

採用された回答

Matt J
Matt J 2025 年 1 月 17 日
編集済み: Matt J 2025 年 1 月 17 日
The only way fminunc knows the number of variables is by looking at numel(x0) where x0 is the initial guess:
xmin = fminunc(fun,x0)
It doesn't look at fun in any way to determine that. So, your current code should be fine.
You could make your initial guess a function of n in some way. Looking at the pattern you have now, you could modify to the following, but it seems to me that the benefit is marginal.
function xmin = problem(n)
x0=[1,zeros(1,n-1)];
switch n
case n=1
fun = @(x) x^2+2*x+3;
case n=2
fun = @(x) x(1)^2+x(2)^2+2*(x(1)+x(2))+3;
case n=3
fun = @(x) x(1)^2+x(2)^2+x(3)^2+2*(x(1)+x(2)+x(3))+3;
end
xmin = fminunc(fun,x0);
end
  3 件のコメント
Matt J
Matt J 2025 年 1 月 17 日
編集済み: Matt J 2025 年 1 月 17 日
function xmin = problem(n)
x0=[1,zeros(1,n-1)];
fun=@(x) sum(polyval([1,2,0],x)) + 3; %3 is not really necessary - constant shift does not affect xmin
xmin = fminunc(fun,x0);
end
Shikun Nie
Shikun Nie 2025 年 1 月 17 日
thanks for your answer. I think it solves my problem. I come out with this code to mimic the problem in my project. It is not the original code.

サインインしてコメントする。

その他の回答 (2 件)

Catalytic
Catalytic 2025 年 1 月 17 日
In the narrow case where your fun is always going to be an anonymous function of x, you could do this -
xmin=problem( @(x) x(1)^2+x(2)^2+x(3)^2+2*(x(1)+x(2)+x(3))+3 )
x0 = 1×3
1 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
xmin = 1×3
-1.0000 -1.0000 -1.0000
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function xmin = problem(fun)
n=numel( unique(extract(func2str(fun) , "x(" + digitsPattern+")")) );
x0=[1,zeros(1,n-1)]
xmin = fminunc(fun,x0 ,optimoptions('fminunc','Display','off') );
end

Stephen23
Stephen23 2025 年 1 月 17 日
編集済み: Stephen23 2025 年 1 月 17 日
"How do I define the objective function fun() such that it automatically adapts to the number of variables."
fun = @(x) sum(x.^2)+2*sum(x)+3;

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

タグ

製品


リリース

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by