I wrote the following formula in order to solve a minimization problem. But when I run the code, I always get the following error:
Error using barrier
Objective function is undefined at initial point. Fmincon cannot continue.
function out = Objectivefunction(x,r,q,K,T,S0,type,marketprice)
%loss function to find optimal heston parameters
%rho = x(5);
%kappa = x(2);
%theta = x(4);
%eta = x(3);
%vol0 = x(1);
%sigma0 = sqrt(vol0);
integration_rule = 1;
Price = zeros(length(T),1);
diffr = zeros(length(T),1);
%FFTCarrMadanHeston(kappa, eta, theta, rho, sigma0, K, T, S0, r, q, type, integrationrule)
%price using FFT
for t = 1:length(T)
Price(t,:) = FFTCarrMadanHeston(x(2), x(3), x(4), x(5), sqrt(x(1)), K(t), T(t), S0, r(t), q, type(t), integration_rule);
diffr(t,:) = marketprice(t) - Price(t);
%diffr(t,:) = (abs(marketprice(t) - Price(t)))/Price(t);
end
out = sqrt(sum((diffr).^2)/length(marketprice));
end
% calibration
v0 = 0.0654; %
kappa0 = 0.6067;
eta0 = 0.0707;
theta0 = 0.2928;
rho0 = -0.7571;
x0 = [v0,kappa0,eta0,theta0,rho0];
x0;
% computation of the interest rate for each maturity
r = spline(interest_rate(:,1), interest_rate(:,2), T);
T = T/360; % maturity in years
%calibration parameters
A = [];
b = [];
Aeq = [];
beq = [];
e = 1e-5;
lb = [e e e e -.999]; % Lower bound on the estimates
ub = [100 10 10 10 .999]; % Upper bound on the estimates
optimpar = fmincon(#(x)Objectivefunction(x,r,q,K,T,S0,type,marketprice), x0, A,b, Aeq, beq, lb, ub);
I do get an outcome when I calculate the value of the objective function in the intitial point. However, once I do it in the fmincon function , it doesn't work anymore
Related
Consider the following problem:
I am now in the third part of this question. I wrote the vectorial loop equations (q=teta2, x=teta3 and y=teta4):
fval(1,1) = r2*cos(q)+r3*cos(x)-r4*cos(y)-r1;
fval(2,1) = r2*sin(q)+r3*sin(x)-r4*sin(y);
I have these 2 functions, and all variables except x and y are given. I found the roots with help of this video.
Now I need to plot graphs of q versus x and q versus y when q is at [0,2pi] with delta q of 2.5 degree. What should I do to plot the graphs?
Below is my attempt so far:
function [fval,jac] = lorenzSystem(X)
%Define variables
x = X(1);
y = X(2);
q = pi/2;
r2 = 15
r3 = 50
r4 = 45
r1 = 40
%Define f(x)
fval(1,1)=r2*cos(q)+r3*cos(x)-r4*cos(y)-r1;
fval(2,1)=r2*sin(q)+r3*sin(x)-r4*sin(y);
%Define Jacobian
jac = [-r3*sin(X(1)), r4*sin(X(2));
r3*cos(X(1)), -r4*cos(X(2))];
%% Multivariate NR
%Initial conditions:
X0 = [0.5;1];
maxIter = 50;
tolX = 1e-6;
X = X0;
Xold = X0;
for i = 1:maxIter
[f,j] = lorenzSystem(X);
X = X - inv(j)*f;
err(:,i) = abs(X-Xold);
Xold = X;
if (err(:,i)<tolX)
break;
end
end
Please take a look at my solution below, and study how it differs from your own.
function [th2,th3,th4] = q65270276()
[th2,th3,th4] = lorenzSystem();
hF = figure(); hAx = axes(hF);
plot(hAx, deg2rad(th2), deg2rad(th3), deg2rad(th2), deg2rad(th4));
xlabel(hAx, '\theta_2')
xticks(hAx, 0:pi/3:2*pi);
xticklabels(hAx, {'$0$','$\frac{\pi}{3}$','$\frac{2\pi}{3}$','$\pi$','$\frac{4\pi}{3}$','$\frac{5\pi}{3}$','$2\pi$'});
hAx.TickLabelInterpreter = 'latex';
yticks(hAx, 0:pi/6:pi);
yticklabels(hAx, {'$0$','$\frac{\pi}{6}$','$\frac{\pi}{3}$','$\frac{\pi}{2}$','$\frac{2\pi}{3}$','$\frac{5\pi}{6}$','$\pi$'});
set(hAx, 'XLim', [0 2*pi], 'YLim', [0 pi], 'FontSize', 16);
grid(hAx, 'on');
legend(hAx, '\theta_3', '\theta_4')
end
function [th2,th3,th4] = lorenzSystem()
th2 = (0:2.5:360).';
[th3,th4] = deal(zeros(size(th2)));
% Define geometry:
r1 = 40;
r2 = 15;
r3 = 50;
r4 = 45;
% Define the residual:
res = #(q,X)[r2*cosd(q)+r3*cosd(X(1))-r4*cosd(X(2))-r1; ... Δx=0
r2*sind(q)+r3*sind(X(1))-r4*sind(X(2))]; % Δy=0
% Define the Jacobian:
J = #(X)[-r3*sind(X(1)), r4*sind(X(2));
r3*cosd(X(1)), -r4*cosd(X(2))];
X0 = [acosd((45^2-25^2-50^2)/(-2*25*50)); 180-acosd((50^2-25^2-45^2)/(-2*25*45))]; % Accurate guess
maxIter = 500;
tolX = 1e-6;
for idx = 1:numel(th2)
X = X0;
Xold = X0;
err = zeros(maxIter, 1); % Preallocation
for it = 1:maxIter
% Update the guess
f = res( th2(idx), Xold );
X = Xold - J(Xold) \ f;
% X = X - pinv(J(X)) * res( q(idx), X ); % May help when J(X) is close to singular
% Determine convergence
err(it) = (X-Xold).' * (X-Xold);
if err(it) < tolX
break
end
% Update history
Xold = X;
end
% Unpack and store θ₃, θ₄
th3(idx) = X(1);
th4(idx) = X(2);
% Update X0 for faster convergence of the next case:
X0 = X;
end
end
Several notes:
All computations are performed in degrees.
The specific plotting code I used is less interesting, what matters is that I defined all θ₂ in advance, then looped over them to find θ₃ and θ₄ (without recursion, as was done in your own implementation).
The initial guess (actually, analytical solution) for the very first case (θ₂=0) can be found by solving the problem manually (i.e. "on paper") using the law of cosines. The solver also works for other guesses, but you might need to increase maxIter. Also, for certain guesses (e.g. X(1)==X(2)), the Jacobian is ill-conditioned, in which case you can use pinv.
If my computation is correct, this is the result:
I'm trying to solve a system of ode's using Runge-kutta, i made a function for RK2(f,h,x0,y0,xfinal) and tried to solve the system shown below with specified IC's. Could someone help fix the code as I get errors and code doesn't work.
ode set
beta = 1/3;
gamma = 1/7;
syms R S I % Symbolic Math Toolbox
N = S+I+R;
ode1 = -(beta*I*S)/N;
ode2 = -(beta*I*S)/N-gamma*I;
ode3 = gamma*I;
odes = [ode1,ode2,ode3];
for j = odes
RK2(j,0.2,0,8e6,7);
end
function [xs,ys] = RK2(f,h,x0,y0,xfinal)
ffnc = matlabFunction(f);
fprintf('\n x y ');
o = 1;
while x0 <= xfinal
fprintf('\n%4.3f %4.3f ',x0,y0); %values of x and y
xs(o) = x0;
ys(o) = y0;
k1 = h*ffnc (x0,y0);
x1 = x0+h;
k2 = h*ffnc (x1,y0+k1);
y1 = y0+(k1+k2)/2;
x0 = x1;
y0 = y1;
o = o+1;
end
end
I have a little problem, fseminf used to work just fine, but now as I reached to it, it happend to produce an error, I have no idea what happend. Here is the code with an example which does not work:
clc;
clear;
close;
% Zdefiniuj funkcje
global g f S
f = #(x) (x(1)-2).^2 + (x(2)-0.2).^2;
g = #(x,s) 5.*x(1).^2.*sin(pi.*sqrt(s))./(1+s.^2) - x(2);
lb = [-1,0];
ub = [1 ,0.2];
S = [0,1];
A = [];
b = [];
Aeq = [];
beq = [];
x0 = [0,0]';
[x,fval,exitflag,output,lambda] = fseminf(f,x0,1,#seminfcon2,A,b,Aeq,beq,lb,ub);
disp('x= ')
x
And seminfcon is defined:
function [c, ceq, K1, s] = seminfcon2(x,s)
global S g
% Dodatkowe parametry
c = [];
ceq = [];
if isnan(s(1,1))
s(1,1)=0.001;
s(1,2)=0;
end
t = S(1):s(1):S(2);
K1 = g(x,t);
The error is when calculating x, meaning in fseminf
I am trying to run fseminf function
f = #(x) (x(1)-2).^2 + (x(2)-0.2).^2;
g = #(x,s) 5*x(1).^2*sin(pi*sqrt(s))/(1+s.^2) - x(2);
lb = [-1,0];
ub = [1 ,0.2];
S = [0,1];
A = [];
b = [];
Aeq = [];
beq = [];
x0 = [0,0];
x = fseminf(f,x0,1,#seminfcon1,A,b,Aeq,beq,lb,ub);
Where:
function [c, ceq, K1, s] = seminfcon1(x,s)
global S g
% No finite nonlinear inequality and equality constraints
c = [];
ceq = [];
% Sample set
if isnan(s)
% Initial sampling interval
s = [0.0001 0];
end
t = S(1):s(1):S(2);
% Evaluate the semi-infinite constraint
K1 = g(x,t);
This is the code I use for creating a finite set from S, which is an interval. I do not understand how it works, why do we use isnan function instead of just declaring s=[0.0001] (which by the way does not work). It is used for fseminf alghoritm, I took the code from an example.
I have a problem using the MATLAB DAE-solvers.
I'm trying to simulate the behaviour of a mechanical system using lagrangien mechanics. To do so, I followed the following tutorial to use MATLAB'sDAE-solvers.
But when I ran my code, I got the following error message:
Warning: Failure at t=5.076437e-01. Unable to meet integration tolerances without reducing the step size below the smallest value allowed
(1.803513e-15) at time t.
In ode15i (line 406)
Trying to find my mistake, I literally copied the code from the tutorial and ran it. The code is as follows:
syms l g m real
syms x(t) y(t) T(t)
eqns = [(m*diff(x(t),2) - T(t)/l*x(t)),
(m*diff(y(t),2) - T(t)/l*y(t) + m*g),
(x(t)^2 + y(t)^2 - l^2) ];
vars = [x(t); y(t); T(t)];
[eqns, vars] = reduceDifferentialOrder(eqns, vars);
if(~isLowIndexDAE(eqns, vars))
[DAEs, DAEvars] = reduceDAEIndex(eqns, vars);
[DAEs, DAEvars] = reduceRedundancies(DAEs, DAEvars);
end
%change to function, set parameters
f = daeFunction(DAEs, DAEvars, m, l, g);
m = 1.0;
r = 1.0;
g = 9.81;
F = #(t, Y, YP) f(t, Y, YP, m, r, g);
%get initial conditions
y0est = [0.5*r; -0.8*r; 0; 0; 0; 0; 0];
yp0est = zeros(7,1);
opt = odeset('RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));
[y0, yp0] = decic(F, 0, y0est, [], yp0est, [], opt);
%simulate
[t,y] = ode15i(F, [0, 5], y0, yp0, opt);