How to append number to array

조회 수: 20 (최근 30일)
Bai chen
Bai chen 2019년 2월 14일
댓글: Luna 2019년 2월 14일
I am new to Matlab.
S0=30;
K=32;
r=0.03;
sigma=0.2;
T=1;
M=10;
error=[];
for i=10:10:360
cat( TRGbinomial(S0,K,r,sigma,T,i)-BSCall(S0,K,r,sigma,T),error);
end
error
I want to append the number to error array.
What can I do with it?
  댓글 수: 2
Luna
Luna 2019년 2월 14일
What are the TRGbinomial and BSCall functions outputs? Share the whole code please.
Bai chen
Bai chen 2019년 2월 14일
function c=TRGbinomial(S0,K,r,sigma,T,n)
%initialize trees and parameters
dt=T/n;
v=r-0.5*sigma^2;
dx=sqrt((sigma^2)*dt+(v^2)*(dt^2));
u=exp(dx);
d=exp(-dx);
p=0.5+0.5*v*dt/dx; %risk neutral probability
%expectd stock prices at time T
for i=0:n
S(i+1,1)=u^(n-i)*(d^i)*S0;
end
%expected payoff at time T (european call option)
payoff=max(S-K,0);
%discount back the payoffs
c(:,n+1)=payoff;
for j=n:-1:1
for i=1:j
c(i,j)=exp(-r*dt)*(p*c(i,j+1)+(1-p)*c(i+1,j+1));
end
end
%return option price
c=c(1,1);
end
function c=BSCall(S0,K,r,sigma,T)
d1=(log(S0/K)+(r+sigma^2/2)*T)/(sigma*sqrt(T));
d2=d1-sigma*sqrt(T);
c=S0*normcdf(d1)-K*exp(-r*T)*normcdf(d2);
end

댓글을 달려면 로그인하십시오.

채택된 답변

Luna
Luna 2019년 2월 14일
Assuming that your function's outputs are 1x1 double, you can use below:
S0=30;
K=32;
r=0.03;
sigma=0.2;
T=1;
M=10;
% error=[];
j = 1; % another counter for for loop because i is used for another calculation
errorArray = zeros(360/10,1); % preallocation
for i=10:10:360
errorArray(j) = TRGbinomial(S0,K,r,sigma,T,i)-BSCall(S0,K,r,sigma,T);
j = j+1;
end
% errorArray will be 36x1 array.
  댓글 수: 2
Bai chen
Bai chen 2019년 2월 14일
Yes, that is much better.
Thank you
Luna
Luna 2019년 2월 14일
Your welcome :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Price and Analyze Financial Instruments에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by