MATLAB: How should I fix the while loop so that “Index exceeds matrix dimensions.” ? Below is the script

index exceeds matrix dimensionswhile loop

fr = input('Find the fifth root of . . .\n ');
gu = input('Give a guess\n ');
k = 1 ;
nrv(1) = gu - ((gu^5-fr)/(5*gu^4));
ar = fr^(1/5) ;
gn(1) = gu ;
while (((abs(nrv(k)-ar)) > 0.0001) && (k ~= 100))
if gn(k) == 0
gn(k) = gn(k) + 0.01;
end
nrv(k) = gn(k) - ((gn(k)^5-fr)/(5*gn(k)^4)) ;
gn(k+1) = nrv(k) ;
k = k + 1 ;
%plot(1:length(k),nrv(k),1:length(k),ar)
end
fprintf('Iteration: %0.0f ',k);
fprintf('Final Estimate: %0.6 ',nrv(k));

Best Answer

In my example below I hardcoded fr and gu. Although I agree with Birdman about pre-allocation, that is not the only problem: nrv(k) looks like it should be nrv(k+1). You also forgot a variable type in your second fprintf, and you forgot(?) a newline.
fr = 0.5;
gu = 5;
ar = fr^(1/5) ;
k_max=100;
%pre-allocate outcomes
nrv=zeros(1,k_max);
gn=zeros(1,k_max);
%initialize vectors
nrv(1) = gu - ((gu^5-fr)/(5*gu^4));
gn(1) = gu ;
k = 1 ;
while (((abs(nrv(k)-ar)) > 0.0001) && (k ~= k_max))
if gn(k) == 0
gn(k) = gn(k) + 0.01;
end
nrv(k+1) = gn(k) - ((gn(k)^5-fr)/(5*gn(k)^4)) ;
gn(k+1) = nrv(k) ;
k = k + 1 ;
%plot(1:length(k),nrv(k),1:length(k),ar)
end
if k ~= k_max
%reduce the output vectors back
gn((k+1):end)=[];
nrv((k+1):end)=[];
end
fprintf('Iteration: %0.0f \n',k);
fprintf('Final Estimate: %0.6f \n',nrv(k));