I have problem with fmincon
2 ビュー (過去 30 日間)
古いコメントを表示
Hello, i need to solve this with optimization toolbox.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/833385/image.png)
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.
0 件のコメント
回答 (1 件)
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
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!