I'm using "Numerical Methods using MATLAB" by Mathews&Fink 4th.ed
There is an example of a program that approximates first derivatives (Program 6.1)
while defining the function, a warning showed up saying "variable appears to change size on
every loop iteration. Consider reallocating for speed"
this is the script:
function [L,n] = difflim(f,x,toler)
%Input - f is the function input as a string 'f'
% - x is the differentiation point
% - toler is the tolerance for the error
%Output-L=[H' D' E']
% H is the vector of step sizes
% D is the vector of approximate derivatives
% E is the vector of error bounds
% - n is the coordinate of the "best approximation"
max1=15;
h=1;
H(1)=h;
D(1)=(feval(f,x+h)-feval(f,x-h))/(2*h);
E(1)=0;
R(1)=0;
for n=1:2
h=h/10;
H(n+1)=h;
D(n+1)=(feval(f,x+h)-feval(f,x-h))/(2*h);
E(n+1)=abs(D(n+1)-D(n));
R(n+1)=2*E(n+1)/(abs(D(n+1))+abs(D(n))+eps);
end
n=2;
while((E(n)>E(n+1))&&(R(n)>toler))&&n<max1
h=h/10;
H(n+2)=h;
D(n+2)=(feval(f,x+h)-feval(f,x-h))/(2*h);
E(n+2)=abs(D(n+2)-D(n+1));
R(n+2)=2*E(n+2)/(abs(D(n+2))+abs(D(n+1))+eps);
end
n=length(D)-1;
L=[H' D' E'];
MATLAB gets stuck when this is executed. I tried to assign H,D,E, and R a zero matrix by adding these lines in the script:
H=zeros;
D=zeros;
E=zeros;
R=zeros;
but it still doesn't work. However one time it did show a correct value in the workspace. But it was still stuck. It's straight out of a textbook, it should work?
also on the 'while' line: there is &&, but the textbook actually just had one &, but MATLAB prompted me to use double &&??