% This is a demo to show how to use the symbolic pkg. to % calculate the derivative of an Anonymous function and then % use the results in normal octave programming. % this is just a formula to start with % have fun and change it if you want to. f=@(x) x.^2 +3*x-1 + 5*x.*sin(x); function NRdemo(f, guess, rlow,rhi) %% The symbolic pkg must be loaded %% f is the input Anonymous function to find the roots of. %% guess is the initial guess %% It should be close to the root you are looking for. %% rlow is the low end of the range for plotting %% rhi is the high end of the range for plotting f % this displays the original function % the nex2 line take the Anonymous function into a symbolic formula syms x; ff=formula(f(x)); % now calculate the derivative of the function ffd=diff(ff); % and convert it back to an Anonymous function df=function_handle(ffd) % now we plot the function and its derivative rs=(rhi-rlow)/10000; x1=rlow:rs:rhi; y=f(x1); y2=df(x1); plot(x1,y,x1,y2) legend ("f","f '"); hold on plot(guess,0,'rx') % plot each guess grid minor on % now use Newton-Raphston method to find the roots finished=false; h=guess while(~finished) hn=h-f(h)/df(h) % this is guess - f/f' if(abs(h-hn)<1e-6) % check to see if we are done finished=true; endif h=hn; plot(h,0,'rx') % plot each guess endwhile plot(h,0,'o') % plot the answer. grid on hold off endfunction % finaly this is the call to the function NRdemo(f,-15,-15,10)