"In an assignment A(I) = B, the number of elements in B and I must be the same."

%%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)

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.
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

Thanks for your answer. I understood why the error came out. I just wanted to find the final value by using for-loop, like "f(1)=1; f(2)=2; for n=3:100 f(n)=f(n-1)+f(n-2) end". But there's a random variable in my function, so I don't know how to do it.
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.

Asked:

on 24 Nov 2013

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!