|
"Anish Goorah" <anish.goorah@gmail.com> wrote in message <fp434u$n1m
$1@fred.mathworks.com>...
> Any brillant ideas as to how I avoid this double loop:
>
> %%Initialization
> iter = 50000;
> simlen = 81;
>
> dPt(:,(1:iter)) = 0.0142;%Initial Price Growth
> price(:,(1:iter)) = 100000;%Initial Price
> stdev = 0.25;
> rho = 0.5;
> c = 0.05;
>
> %Simluation
>
> dist = stdev*randn(simlen+1,iter);
>
> for i=1:iter
> for j=1:simlen
> dPt(j+1,i) = c+rho*dPt(j,i)+dist(j,i);
> price(j+1,:) = price(j,:).*(1+dPt(j+1,:));
> end
> end
-------
I need some clarification here, Anish.
1. When you write dPt(:,(1:iter)) = 0.0142, has the array 'dPt' been previously
defined, and if so, what is its size? Is it simlen+1 by iter? If it hasn't been
defined, it is not a good idea to force dPt to have its rows allocated one at a
time, as it would be in the inner loop. That slows down computation
markedly. You need to allocate the entire array initially even if all but the first
row start out as zeros, as in:
dPt = zeros(simlen+1,iter); dPt(1,:) = 0.0142;
2. In the inner loop did you mean to write
price(j+1,i) = price(j,i).*(1+dPt(j+1,i)) ?
What you have at present does not make a lot of sense. All the columns of
'price' are being defined in terms of 'dPt' columns, some of which have
apparently not yet been calculated, at least in a meaningful way.
3. The way you have set up this iteration, the first row of dPt does not have
any effect on values in the 'price' array. Was that your intent?
Assuming your answers to the above are what I think they will be, you can
use just one for-loop for computing 'dPt' and vectorize 'price' completely.
for j=1:simlen
dPt(j+1,:) = c+rho*dPt(j,:)+dist(j,:);
end
price = cumprod([price(1,:);dPt(2:simlen+1,:)+1],1);
Roger Stafford
|