Is there something wrong with my anonymous function definition?
10 ビュー (過去 30 日間)
古いコメントを表示
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!
0 件のコメント
採用された回答
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
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)
x = [x1, x2];
% B
fun1 = @(x) ((x(1) - 3.67.*10^-6).^2 + (x(2)-3.67.*10^-7).^2);
B = fun1(x)
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)
% 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)
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)
% 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)
Similarly, one can adjust ver B if x1 and x2 are column vectors.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!