# Nested For Loops - Using a value from first loop within the second loop

4 views (last 30 days)
Pete on 24 Feb 2013
I am creating a for loop and am in need of some advice.
I have set up a for loop which uses a 200 length i vector and a 200 length j vector and this loops in order to create a 2D matrix where effectively every value of i is multiplied by a j.
The code for this part is as follows:
for i=1:length(x)
pxt(1,i) = k/A*((x(1,i)-B)/A)^(k-1)*exp(-((x(1,i)-B)/A)^k);
for j= 1:length(y)
pyt(j,1) = AlphaEst/BetaEst*(y(1,j)/BetaEst)^(AlphaEst-1)*exp(-(y(1,j)/BetaEst)^AlphaEst);
end
end
Matrix = pxt*pyt
This works fine for vectors x and y (200 length) and when k,A,B,AlphaEst and BetaEst are all constant. I now want to write AlphaEst and BetaEst as functions of the x value at that given point in the loop. I.E whichever x value has just been used in the first part of the loop I would like to use again in the second part.
Can anyone help with how to write this in matlab?

Shaun VanWeelden on 24 Feb 2013
What you are looking for is actually pretty easy to do, the key is to realize that the i from the for loop is actually a variable, so just like you can compute pxt each time, you can also compute AlphaEst and BetaEst each time and use them in your nested loop, something like this should work for you:
for i=1:length(x)
pxt(1,i) = k/A*((x(1,i)-B)/A)^(k-1)*exp(-((x(1,i)-B)/A)^k);
AlphaEst=yourFunction(i);
BetaEst=yourFunction(i);
for j= 1:length(y)
pyt(j,1) = AlphaEst/BetaEst*(y(1,j)/BetaEst)^(AlphaEst-1)*exp(-(y(1,j)/BetaEst)^AlphaEst);
end
end
Matrix = pxt*pyt

Walter Roberson on 25 Feb 2013
pyt(j,1) = AlphaEst(x(1,i))/BetaEst(x(1,i))*(y(1,j)/BetaEst(x(1,i)))^(AlphaEst(x(1,i))-1)*exp(-(y(1,j)/BetaEst(x(1,i))^AlphaEst(x(1,i)))
or for greater efficiency,
Lx = length(x);
Ly = length(y);
pxt = zeros(1, Lx);
pyt = zeros(Ly, 1);
for i = 1 : Lx
xi = x(i);
pxt(i) = k/A*((xi-B)/A)^(k-1)*exp(-((xi-B)/A)^k);
AE = AlphaEst(xi);
BE = BetaEst(xi);
for j = 1 : Ly
pyt(j) = AE/BE*(y(j)/BE)^(AE-1)*exp(-(y(j)/BE)^AE);
end
end
Matrix = pxt * pyt
and then you can vectorize the "for j" loop to
pyt = AE/BE .* (y ./ BE).^(AE-1) * exp( -(y ./ BE).^AE );
After that I would start to wonder why you overwrite pyt for each "for i" value, and then do not use pyt until after the end of the double loop, thus effectively using only the pyt that corresponds to maximum x...