简体   繁体   中英

Matlab Error A(I) = B

I am currently looking at Binomial Option Pricing. I have written the code below, which works fine, when you enter the variables in one at a time. However, entering each set of values is very tedious, and I need to be able to analyse a large set of data. I have created arrays for each of the variables. But, I keep getting the error; A(I) = B, the number of elements in B must equal I. The function is shown below.

function C = BinC(S0,K,r,sig,T,N);

% PURPOSE: 
% To return the value of a European call option using the Binomial method 
%-------------------------------------------------------------------------
% INPUTS:
% S0      - The initial price of the underlying asset
% K       - The strike price 
% r       - The risk free rate of return, expressed as a decimal
% sig     - The volatility of the underlying asset, expressed as a decimal
% T       - The time to maturity, expressed as a decimal
% N       - The number of steps
%-------------------------------------------------------------------------

dt = T/N;
u = exp(sig*sqrt(dt));
d = 1/u;
p = (exp(r*dt) - d)/(u - d);

S = zeros(N+1,1);           

% Price of underlying asset at time T
for n = 1:N+1
S(n) = S0*(d^(N+1-n))*(u^(n-1));
end

% Price of Option at time T
for n = 1:N+1
C(n) = max(S(n)- K, 0);
end

% Backtrack to get option price at time 0
for i = N:-1:1
for n = 1:i
C(n) = exp(-r*dt)*(p*C(n+1) + (1-p)*C(n));
end
end

disp(C(1))

After importing my data, I entered this in to the command window.

for i=1:20
w(i)= BinC(S0(i),K(i),r(i),sig(i),T(i),N(i));
end

When I enter w, all I get back is w = []. I have no idea how I can make A(I) = B. I apologise, if this is a very silly question, but I am new to Matlab and in need of help. Thanks

Your function computes an entire vector C , but displays only C(1) . This display is deceptive: it makes you think the function is returning a scalar, but it's not: it's returning the entire vector C , which you try to store into a scalar location.

The solution is simple: Change your function definition to this (rename the output variable):

function out = BinC(S0,K,r,sig,T,N);

Then at the last line of the function, remove the disp , and replace it with

out = C(1);

To verify all of this (compare with your non-working example), try calling it by itself at the command line, and examine the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM