Error: using fmincon FMINCON requires all values returned by functions to be of data type double.

2 次查看(过去 30 天)
I am getting an error when running this code. It will be helpful if you could help.
%% Input
syms d
G1 = 3e6;
p = 1;
G0 = 1e8;
k0 = 0.004;
k1 = 0.003;
%% Calculation
D = [cos(k1*d) sin(k1*d)*p/(G1*k1)*1i; sin(k1*d)*(G1*k1)/p*1i cos(k1*d)];
L = [2*p/k0*cos(5*k0) sin(5*k0)*2*p/k0*1i; sin(5*k0)*2*G0*1i 2*G0*cos(5*k0)];
B = D*L;
B1 = B(1,1);
B2 = B(1,2);
B3 = B(2,1);
B4 = B(2,2);
answer = (2*p*(B4-B3)-2*k0*G0*(B2-B1))/(k0*(B1+B2)*(B4-B3)-k0*(B4+B3)*(B2-B1));
magnitude = abs(answer);
%% Optimization
fun = @(d)magnitude;
d0 = 0.5;
A = [];
b = [];
Aeq = [];
beq = [];
lb = 0;
ub = Inf;
[s,fval] = fmincon(fun,d0,A,b,Aeq,beq,lb,ub); %minimize

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-11-9
Use matlabFunction to convert the symbolic expression to an anonymous function -
%% Input
syms d
G1 = 3e6;
p = 1;
G0 = 1e8;
k0 = 0.004;
k1 = 0.003;
%% Calculation
D = [cos(k1*d) sin(k1*d)*p/(G1*k1)*1i; sin(k1*d)*(G1*k1)/p*1i cos(k1*d)];
L = [2*p/k0*cos(5*k0) sin(5*k0)*2*p/k0*1i; sin(5*k0)*2*G0*1i 2*G0*cos(5*k0)];
B = D*L;
B1 = B(1,1);
B2 = B(1,2);
B3 = B(2,1);
B4 = B(2,2);
answer = (2*p*(B4-B3)-2*k0*G0*(B2-B1))/(k0*(B1+B2)*(B4-B3)-k0*(B4+B3)*(B2-B1));
magnitude = abs(answer);
%% Optimization
fun = matlabFunction(magnitude, 'Vars', d);
d0 = 0.5;
A = [];
b = [];
Aeq = [];
beq = [];
lb = 0;
ub = Inf;
[s,fval] = fmincon(fun,d0,A,b,Aeq,beq,lb,ub) %minimize
Local minimum found that satisfies the constraints. Optimization completed because the objective function is non-decreasing in feasible directions, to within the value of the optimality tolerance, and constraints are satisfied to within the value of the constraint tolerance.
s = 0.0096
fval = 1.0000

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by