MATLAB: Basic for loop problem

for loopproblem

thanks

Best Answer

You have to store the results in a matrix, while in you code the result was stored in a scalar an overwritten in each iteration:
tVec = 1:1:20;
rVec = -.8:.1:0.9;
tNum = length(tVec);
rNum = length(rVec);
Test_vals = zeros(tNum, rNum);
for it = 1:tNum
t = tVec(it);
for ir = 1:rNum
r = rVec(ir);
Test_vals(it, ir) = (((1/f)*(w/(g+t*w)))-1)*[1 - (normcdf(phid/(1+(r/(2*f))*[w/(g+t*w)]),(g/(g+w))*phi0 + (w/(g+w)*phid),(sqrt(w)/(g+w))))]*r + ((1/(4*f^2))*(w/(g+1*w))^2)*([1 - (normcdf(phid/(1+(r/(2*f))*[w/(g+t*w)]),(g/(g+w))*phi0 + (w/(g+w)*phid),(sqrt(w)/(g+w))))]*r^2 -normcdf(phid/(1+(r/(2*f))*[w/(g+t*w)]),(g/(g+w))*phi0 + (w/(g+w)*phid),(sqrt(w)/(g+w))));
end
end
Here the indices it and ir are used, which are positive integers. You cannot use r and t directly as indices.
Note that the square brackets are the concatenation operator. For scalars they are working as parenthesis, but this looks confusing.
The code is nearly unreadable and a debugging will be impeded by this. Better create some temporary variables to get it leaner:
c1 = w / (g + t * w);
c2 = g / (g + w);
c3 = sqrt(w) / (g + w);
c4 = normcdf(phid/(1+(r/(2*f))*c1), c2*phi0 + (w/(g+w)*phid), c3);
Test_vals (it, ir) = (c1 / f - 1) * (1 - c4) * r + ...
(w / (g + 1 * w)) ^ 2) / (4 * f ^ 2) * ...
((1 - c4) * r ^ 2 - c4);