Error using plot: vectors must be the same lengths
Afficher commentaires plus anciens
I am trying to plot two function in the same file; however, I am getting the following error: "Error using plots: vectors must be the same lengths". The rest of the code works. The only problem in in the plotting. I can plot them individually, but I cannot plot them together. Please help me to find a way to do this. Here is my code:
clear; clc;
% Definition of all variables and functions
% Stock price
variance = 1; % Variance
average = 0; % Average
t = 10000; % Time
stock_value(1) = 200; % Initial stock value
% Delta hedging
K = 200; % Strike price
r = 0.05; % Risk free interest rate
sigma = 0.4; % Volatility of asset
tau = 1; % Time constant
d1(1) = (1/sigma*sqrt(tau))*(log(stock_value(1)/K)+(r+(sigma^2)/2)*tau);
N(1) = normcdf(d1(1));
delta(1) = exp(-r*tau)*N(1);
for j=2:t
% Monte Carlo somulation of stock price
stock_value(j) = stock_value(j-1) + randn*variance;
if stock_value(j) > 1
variance = 0.5;
elseif stock_value < -1
stock_value = 2;
else
variance = 1;
end
% Delta hedging
d1(j) = (1/sigma*sqrt(tau))*(log(stock_value(j)/K)+(r+(sigma^2)/2)*tau);
% Cumulative normal distribution
N(j) = normcdf(d1(j));
% Delta
delta(j) = exp(-r*tau)*N(j);
end
% Plots
x = linspace(0,t);
y1 = stock_value;
y2 = delta;
tiledlayout(2,1)
% Top plot
ax1 = nexttile;
plot(ax1,x,y1)
title(ax1,'Stock Value')
ylabel(ax1,'S_t')
% Bottom plot
ax2 = nexttile;
plot(ax2,x,y2)
title(ax2,'Delta to Maturity')
ylabel(ax2,'delta_t')
% Show results
% Stock value
fprintf('initial stock value =%.8f\n',stock_value(1))
fprintf('stockvalue at first quarter =%.8f\n',stock_value(t/4))
fprintf('stockvalue at second quarter =%8f\n',stock_value(t/2))
fprintf('stockvalue at third quarter =%.8f\n',stock_value((3*t)/4))
fprintf('final stockvalue =%.8f\n',stock_value(t))
% Delta
fprintf('initial delta =%.8f\n',delta(1))
fprintf('delta at first quarter =%.8f\n',delta(t/4))
fprintf('delta at second quarter =%.8f\n',delta(t/2))
fprintf('delta at third quarter =%.8f\n',delta((3*t)/4))
fprintf('delta at maturity =%.8f\n',delta(t))
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Equity Derivatives dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!