Maximization symbolic function with piecewise symbolic functions
Show older comments
Hello,
i have the following code:
syms R K L ext_mon
T = 100;
%Company
gamma = 0.03;
A_0 = 100;
debt = 0;
ext_cost = symfun(ext_mon*1.03^T,ext_mon);
%Insurer
AI_0 = 200;
LI_0 = 100;
mu_L = 0.02;
mu_A = 0.03;
sigma_L = 0.002;
sigma_A = 0.001;
prem = symfun(R+K,[R K]);
A_T = symfun((1+gamma)*(A_0+prem),[R K]);
expAI = symfun((AI_0 + prem(R,K))* exp((mu_A + (sigma_A^2/2))*T),[R K]);
expLI_tilde= LI_0*exp((mu_L + (sigma_L^2/2))*T);
X= symfun(piecewise(L<R,L,R<=L<=K,R,L>K,R+L-K),[R K]);
Y= symfun(piecewise(L<R,0,R<=L<=K,L-R,L>K,K-R),[R K]);
D = symfun(piecewise((Y(R,K) - expAI(R,K) - expLI_tilde)>0,Y(R,K) - expAI(R,K) - expLI_tilde,0),[R K]);
S_T = symfun(A_T - debt - L - X - D,[R K]);
Investment = symfun(S_T(R,K) + ext_mon,[R K]);
GrossReturn = symfun(Investment(R,K)*1.03^T,[R K]);
Profit = symfun(GrossReturn(R,K) - Investment(R,K) - ext_cost(ext_mon),[R K ext_mon]);
I want now to maximize "Profit" under R,K and ext_mon.
When i use fminsearch(-Profit,[0 1 0]), i get the error
fminsearch(-Profit,[0 1 0])
Error using symfun/subsref
Invalid argument at position 2. Symbolic function expected 3 input arguments but received 1.
Error in fminsearch (line 200)
I tried already to convert the symbolic function with matlabFunction, but there i get the error
Unable to generate code for piecewise for use in anonymous functions.
Can someone help me, how i can maximize the symbolic function ?
Best
Answers (1)
syms R K L ext_mon
T = 100;
%Company
gamma = 0.03;
A_0 = 100;
debt = 0;
ext_cost = symfun(ext_mon*1.03^T,ext_mon);
%Insurer
AI_0 = 200;
LI_0 = 100;
mu_L = 0.02;
mu_A = 0.03;
sigma_L = 0.002;
sigma_A = 0.001;
prem = symfun(R+K,[R K]);
A_T = symfun((1+gamma)*(A_0+prem),[R K]);
expAI = symfun((AI_0 + prem(R,K))* exp((mu_A + (sigma_A^2/2))*T),[R K]);
expLI_tilde= LI_0*exp((mu_L + (sigma_L^2/2))*T);
X= symfun(piecewise(L<R,L,R<=L<=K,R,L>K,R+L-K),[R K]);
Y= symfun(piecewise(L<R,0,R<=L<=K,L-R,L>K,K-R),[R K]);
D = symfun(piecewise((Y(R,K) - expAI(R,K) - expLI_tilde)>0,Y(R,K) - expAI(R,K) - expLI_tilde,0),[R K]);
S_T = symfun(A_T - debt - L - X - D,[R K]);
Investment = symfun(S_T(R,K) + ext_mon,[R K]);
GrossReturn = symfun(Investment(R,K)*1.03^T,[R K]);
Profit = symfun(GrossReturn(R,K) - Investment(R,K) - ext_cost(ext_mon),[R K ext_mon]);
Profit
negProfit = -Profit
tn = tempname + ".m";
negProfitfun = matlabFunction(negProfit, 'vars', {[R, K, ext_mon, L]}, 'File', tn, 'optimize', false)
ph = fileparts(tn);
addpath(ph)
opts = optimset(@fminsearch);
opts.MaxFunEvals = 1e5;
opts.MaxIter = 1e5;
[bestvars, negprofit] = fminsearch(negProfitfun, [0 1 0 0], opts);
profit = -negprofit;
fprintf('Profit %g at R = %g, K = %g, ext_mon = %g, L = %g\n', profit, bestvars);
Categories
Find more on Optimization Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
