Is there something wrong with my anonymous function definition?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Akzeptierte Antwort
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
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)
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 Kommentare
Siehe auch
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!