Is there something wrong with my anonymous function definition?

9 Ansichten (letzte 30 Tage)
Sumeet
Sumeet am 12 Feb. 2023
Kommentiert: Sumeet am 12 Feb. 2023
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!

Akzeptierte Antwort

Torsten
Torsten am 12 Feb. 2023
Bearbeitet: Torsten am 12 Feb. 2023
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".

Weitere Antworten (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov am 12 Feb. 2023
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.

Kategorien

Mehr zu Entering Commands finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by