Is there something wrong with my anonymous function definition?

10 ビュー (過去 30 日間)
Sumeet
Sumeet 2023 年 2 月 12 日
コメント済み: Sumeet 2023 年 2 月 12 日
A-> fun1 = @(x1,x2) (x1 - 3.67.*10^-6).^2 + (x2-3.67.*10^-7).^2;
B-> fun1 = @(x) ((x(1) - 3.67.*10^-6).^2 + (x(2)-3.67.*10^-7).^2);
I wish to define my function as in A, however I run into errors saying "Failure in initial objective Function evaluation. FMINCON cannot continue.". Only the function in B runs smoothly.
Wished to check if there's something I'm missing out on. Thanks!

採用された回答

Torsten
Torsten 2023 年 2 月 12 日
編集済み: Torsten 2023 年 2 月 12 日
Fmincon expects fun1 to have one vector of length n of parameter values as input, not n scalar values as for your function fun1. Thus you have to modify your function to fit what fmincon needs.
Use
fun1 = @(x1,x2) (x1 - 3.67e-6).^2 + (x2-3.67e-7).^2;
F = @(x) fun1(x(1),x(2))
and pass F to "fmincon".

その他の回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023 年 2 月 12 日
If x1 and x2 are scalars, then A and B are equivalent:
% A
fun1 = @(x1,x2) (x1 - 3.67.*10^-6).^2 + (x2-3.67.*10^-7).^2;
x1 = 1;
x2 = 2;
A =fun1(x1, x2)
A = 5.0000
x = [x1, x2];
% B
fun1 = @(x) ((x(1) - 3.67.*10^-6).^2 + (x(2)-3.67.*10^-7).^2);
B = fun1(x)
B = 5.0000
If x1 and x2 are not scalar. x1 and x2 are vectors (col or row) of thte same size. Then A and B are not the same - see:
% A
fun1 = @(x1,x2) (x1 - 3.67.*10^-6).^2 + (x2-3.67.*10^-7).^2;
x1 = 1:3;
x2 = -3:-1;
A = fun1(x1, x2)
A = 1×3
10.0000 8.0000 10.0000
% B
fun1 = @(x) ((x(1) - 3.67.*10^-6).^2 + (x(2)-3.67.*10^-7).^2);
x1 = 1:3;
x2 = -3:-1;
x = [x1, x2];
B = fun1(x)
B = 5.0000
Now, to make both equivalent:
% A
fun1 = @(x1,x2) (x1 - 3.67.*10^-6).^2 + (x2-3.67.*10^-7).^2;
x1 = 1:3;
x2 = -3:-1;
A = fun1(x1, x2)
A = 1×3
10.0000 8.0000 10.0000
% B
fun1 = @(x) ((x(1,:) - 3.67.*10^-6).^2 + (x(2,:)-3.67.*10^-7).^2);
x1 = 1:3;
x2 = -3:-1;
x = [x1; x2];
B = fun1(x)
B = 1×3
10.0000 8.0000 10.0000
Similarly, one can adjust ver B if x1 and x2 are column vectors.

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by