Error using plot: vectors must be the same lengths

5 views (last 30 days)
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;
variance = 1;
% 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);
% Plots
x = linspace(0,t);
y1 = stock_value;
y2 = delta;
% Top plot
ax1 = nexttile;
title(ax1,'Stock Value')
% Bottom plot
ax2 = nexttile;
title(ax2,'Delta to Maturity')
% 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))

Accepted Answer

Clayton Gotberg
Clayton Gotberg on 21 Apr 2021
Edited: Clayton Gotberg on 21 Apr 2021
The problem is that x and y1 (and y2) are different sizes. Look at the linspace documentation -
A = linspace(start,end);
returns 100 evenly spaced points between the start and end values. If you want to create a vector climbing by 1 from zero to the value of t, instead try
t_vec = 0:t; % start:step:end (if step isn't included it's assumed to be 1)
Also note that your other arrays start at t = 1, so you'll likely want this to start at 1 as well.
When I change
x = linspace(0,t);
x = 1:t;
I am able to execute your code without other errors.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!

Translated by