Is there something wrong with my anonymous function definition?

17 次查看(过去 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!

采纳的回答

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
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 CenterFile Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by