I have problem with fmincon

조회 수: 2 (최근 30일)
Yusuf Kenan Efe Aybar
Yusuf Kenan Efe Aybar 2021년 12월 13일
답변: Alan Weiss 2021년 12월 14일
Hello, i need to solve this with optimization toolbox.
My first attempt was this code but this is not optimization toolbox.
clearvars; clc; clear; close all;
%%
n=0; % initial n
nopt = double(u(n)); % converts symbolic variable to double variable
%% while loop
while nopt < 49.5
n=n+1;
nopt = double(u(n));
end
%% display results
fprintf('Minimum harmonies should be selected is %d for contain %s of the modulated signal power.\n',n,'%99');
fprintf('Also, with this harmonies we can contain up to %s%.2f of the modulated signal power.\n','%',nopt*2);
%% function we want to solve
function U = u(x)
syms k;
B = symsum((besselj(k,5)).^2,k,1,x);
A = (besselj(0,5))^2;
U = 50*(A+2.*B);
end
And i tried with fmincon but i have some errors.
clearvars; clc; clear; close all;
%%
options = optimoptions("fmincon",...
"Algorithm","interior-point",...
"EnableFeasibilityMode",true,...
"SubproblemAlgorithm","cg");
%%
x0=0;
s = fmincon(@objfun,x0,[],[],[],[],[],[],@confun,options);
%%
function f = objfun(x)
A = (besselj(0,5))^2;
syms k;
B = symsum((besselj(k,5)).^2,k,1,x);
%B = 0.0;
%for k=1:1:x
% B = B + besselj(k,5).^2;
%end
F = 50.*(A+2.*B);
f = matlabFunction(F);
end
%%
function [c,ceq] = confun(x)
c = 49.5 - objfun(x);
%c = matlabFunction(C);
ceq=[];
end
with these errors:
Operator '-' is not supported for operands of type 'function_handle'.
Error in hw2v2>confun (line 24)
c = 49.5 - objfun(x);
Error in fmincon (line 655)
[ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});
Error in hw2v2 (line 9)
s = fmincon(@objfun,x0,[],[],[],[],[],[],@confun,options);
>>
Thanks in advance.

답변 (1개)

Alan Weiss
Alan Weiss 2021년 12월 14일
Do not use symbolic variables with Optimization Toolbox functions, unless you convert them to function handles using matlabFunction first. See, for example, Calculate Gradients and Hessians Using Symbolic Math Toolbox™.
You might find it easier to use the Problem-Based Optimization Workflow instead. In that approach, you create symbolic-type optimization variables (NOT using sym or syms, but instead using optimvar).
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by