MATLAB: Array indices must be positive integers or logical values. error

array indices must be positive integers or logical values erro

New to MatLab. I am trying to graph a tree for X and keep receiving the error "Array indices must be positive integers or logical values erroArray indices must be positive integers or logical values error."
N=100;
T=1;
h=T/N;
KAPPA = 0.1;
x = zeros(N+1,N+1);
ju = x;
jd = x;
pu = x;
pd = x;
% define x grid
for nIndex=1:N+1
n = nIndex-1;
for jIndex=1:N+1
j = jIndex-1;
x(nIndex,jIndex)=(2*j-n)*sqrt(h);
end
end
% fill in ju and jd for each cell
for nIndex=1:N
n = nIndex-1;
for jIndex=1:N+1
j = jIndex-1;
ju(nIndex, jIndex) = n+1;
for j_star = j+1:n+1
if x(nIndex,jIndex)+mu_x(KAPPA,x(nIndex,jIndex))*h < x(nIndex + 1,j_star)
ju(nIndex, jIndex) = j_star;
break
end
end
jd(nIndex, jIndex) = 0;
for j_star = 1:j
if x(nIndex,jIndex)+mu_x(KAPPA,x(nIndex,jIndex))*h > x(nIndex + 1,j_star)
jd(nIndex, jIndex) = j_star;
break
end
end
end
end
% fill in pu and pd for each cell
for nIndex=1:N
n = nIndex-1;
for jIndex=1:N+1
j = jIndex-1;
pu_numerator = mu_x(KAPPA,x(nIndex,jIndex)) - x(nIndex+1,jd(nIndex,jIndex));
pu_denominator = x(nIndex+1,ju(nIndex,jIndex)) - x(nIndex+1,jd(nIndex,jIndex));
pu_check = pu_numerator / pu_denominator;
pu(nIndex,jIndex) = min(1,max(0,pu_check));
pd(nIndex,jIndex) = 1 - pu(nIndex,jIndex);
end
end
this is in a a defrent script
function retValue=mu_x(KAPPA, x)
retValue = -KAPPA*x;

Best Answer

You initialize all jd locations to 0. You have a conditional test about assigning a different value to the jd entry -- which implies that when the test is not true that some jd entries are left at 0.
When you calculate pu_numerator, you have jd(nIndex,jIndex), which can be 0 because some jd entries are 0. You use that as the second index into x, so you are sometimes asking to index x(nIndex+1,0) which is not valid.
Perhaps
if jd(nIndex,jIndex) == 0
pu(nIndex,jIndex) = nan;
pd(nIndex,jIndex) = nan;
else
pu_numerator = ..... etc
end