"In an assignment A(I) = B, the number of elements in B and I must be the same."
Info
This question is closed. Reopen it to edit or answer.
Show older comments
%%Option pricing with stochastic volatility by Monte Carlo
S(1)=1065;
K=1100;
r=0.0125;
VL=0.04;
V(1)=0.04;
a=0.05;
c=0.4;
rho=-0.5;
t=1/250;
M=1000;
for n=2:(M+1)
V(n)=V(n-1)+a*(VL-V(n-1))*t+c*sqrt(t*abs(V(n-1)))*(rho*randn(M,1)+sqrt(1-rho^2)*randn(M,1));
end
for n=2:(M+1)
S(n)=S(n-1)*exp((r-0.5*V(n-1))*t+sqrt(t*V(n-1))*randn(M,1));
end
option_vals=max(S(n)-K,0);
expected_vals=mean(option_vals);
int=1.96*std(option_vals)/sqrt(M);
call_val=exp(-r*t*250)*expected_vals;
display(call_val)
display([call_val-int call_val+int])
%% Why is there a "In an assignment A(I) = B, the number of elements in B and I must be the same" in here?
%% It seems like an iterated function problem. Can someone help me figure it out? Thanks!
Answers (2)
Matt J
on 24 Nov 2013
It happens when you do things like this
>> a=1:5; a(1:2)=1:6
In an assignment A(I) = B, the number of elements in B and I must be the same.
Roger Stafford
on 24 Nov 2013
0 votes
In the first for-loop you have a 1000-element vector on the right side because of the two "randn(M,1)" which is to be assigned to the scalar quantity V(n). That will produce the error message you saw, because matlab doesn't know how to accomplish that. The same is true with the second for-loop. What is it you intended there?
2 Comments
Jimmy
on 24 Nov 2013
Roger Stafford
on 25 Nov 2013
When you write randn(M,1) it gives you an entire sequence of a thousand random values all at once, so don't write your code that way. Do this instead:
for n=2:(M+1)
V(n) = V(n-1)+a*(VL-V(n-1))*t + ...
c*sqrt(t*abs(V(n-1)))*(rho*randn+sqrt(1-rho^2)*randn);
end
or else do this:
r1 = randn(M,1); r2 = randn(M,1);
for n=2:(M+1)
V(n) = V(n-1)+a*(VL-V(n-1))*t + ...
c*sqrt(t*abs(V(n-1)))*(rho*r1(n-1)+sqrt(1-rho^2)*r2(n-1));
end
Either way you are then assigning a scalar value to a scalar value which makes matlab happy.
If you want only the final value of V, then don't bother to index it:
V = V+a*(VL-V)*t + ...
Note that if you use random values to generate V and S, your results will of course vary from one run to the next run, perhaps drastically, depending on what random values you happen to receive from 'randn'.
This question is closed.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!