title: work backwards to price the option at each nodes
body: <p>I am trying to work backwards and price the option at each nodes in Matlab , but when I do it I don't get the right answer. I want to find the value of the call option at time 0. Any help/suggestions would be greatly appreciated.
  Thank you</p>
  
  <pre><code>% generate the tree
  K=100; r=0.05; delta=0.1; T=1; sigma=0.2; n=100; b=2; dt=1/3;
  S1=130*ones(1,1); % stock price at time t = 0
  S2=zeros(b,1); % stock price at time t = 1/3
  S3=zeros(b*b,1); % stock price at time t = 2/3
  S4=zeros(b*b*b,1); % stock price at time t = 1
  t=[0;1/3;2/3;1];
  
  for i=1:b
      z=normrnd(0,1);
      S2(i)=S1*exp((r-delta-(sigma)^2)*(dt)+sigma*sqrt(dt)*z);
  end
  
  for i=1:b
      for j=1:b
      z=normrnd(0,1);
      S3((i-1)*b+j)=S2(i)*exp((r-delta-(sigma)^2)*(dt)+sigma*sqrt(dt)*z);
      end
  end
  
  for i=1:b*b
      for j=1:b
      z=normrnd(0,1);
      S4((i-1)*b+j)=S3(i)*exp((r-delta-(sigma)^2)*(dt)+sigma*sqrt(dt)*z); 
      end
  end
  
  matrix=NaN*ones(size(S4,1),4);
  %NaN=0;
  matrix(1:size(S1,1),1)=S1;
  matrix(1:size(S2,1),2)=S2;
  matrix(1:size(S3,1),3)=S3;
  matrix(1:size(S4,1),4)=S4;
  S=[S1;S2;S3;S4];
  
  % work backwards to price the option at each nodes
  theta4=max(S4-K,0)
  for i=1:length(S3)
      theta3(i)=max(S3(i)-K,exp(-r*(1/3))*theta4(i))
  end
  for i=1:length(S2)
      theta2(i)=max(S2(i)-K,exp(-r*(1/3))*theta3(i))
  end
  theta1=max(S1-K, exp(-r*(1/3))*theta2(i))
  </code></pre>