简体   繁体   English

Matlab错误A(I)= B

[英]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. A(I)= B,B中的元素数必须等于I。该函数如下所示。

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 = []. 输入w时,我得到的只是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. 我不知道如何使A(I)=B。如果这是一个非常愚蠢的问题,我表示歉意,但是我是Matlab新手,需要帮助。 Thanks 谢谢

Your function computes an entire vector C , but displays only C(1) . 您的函数将计算整个向量C ,但仅显示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. 这种显示具有欺骗性:它使您认为函数正在返回标量,但并非如此:它返回了整个向量C ,您试图将其存储到标量位置。

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 然后在函数的最后一行,删除disp ,并将其替换为

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. 要验证所有这些(与您的非工作示例比较),请尝试在命令行上单独调用它,然后检查输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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