Troubles on differentiation inside a function

1 view (last 30 days)
Do you guys know how to differentiate a function inside a function?
I want to input a function, ask the code to differentiate it and use both function and its derivative in a loop.
function [zero] = newton_raphson (x0,precisao,funcao)
%Estimates the root of a function
syms x
f=funcao(x);
derivada=diff(f,x);
x(1)=x0;
erro=realmax;
i=1;
while erro > precisao
x(i+1)=x(i)-f(x(i))/derivada(x(i));
erro = abs (x(i+1)-x(i));
i=i+1;
end
disp(['The estimate root is ' num2str(x(end)) ' with ' num2str(i) ' iteractions.'])
return
The error message when i enter "newton_raphson(2,10^-3, @(x) x+1): ??? Error using ==> mupadmex Error in MuPAD command: Index exceeds matrix dimensions.
Error in ==> sym.sym>sym.subsref at 1366
B = mupadmex('mllib::subsref',A.s,inds{:});
Error in ==> newton_raphson at 16
x(i+1)=x(i)-f(x(i))/derivada(x(i));
Thanks!
  3 Comments
Ryan
Ryan on 21 Jul 2012
I'm guessing f isn't in a proper format for diff. What is "func"? What class is f? What does unique(f) return?
Arthur
Arthur on 22 Jul 2012
Sorry, you guys. My variables are on portuguese, i tried to rename it on english to make it easier here, but it seems it just messed up. Code fixed as the original, with the message error.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 22 Jul 2012
deri=diff(f,x) %differentiate against a variable
Caution: what results will be a symbolic function, but later you try to invoke it as if it is a numeric function in the line
x(i+1)=x(i)-f(x(i))/deri(x(i));
I suggest you examine matlabFunction()
  2 Comments
Arthur
Arthur on 22 Jul 2012
I tried, but still couldn't do it.
The code on the while loop is ok. I tested it removing the variable funcao and putting a function and its derivative on the code, below the loop like this:
while erro > precisao
x(i+1)=x(i)-f(x(i))/derivada(x(i));
erro = abs (x(i+1)-x(i));
i=i+1;
end
disp(['The estimate root is ' num2str(x(end)) ' with ' num2str(i) ' iteractions.'])
return
function y=funcao(x);
y=x^2-2*x+1;
return
function y=derivada(x);
y=2*x-2;
return
Thank you for the attention.
Walter Roberson
Walter Roberson on 22 Jul 2012
derivada = matlabFunction( diff(f,x), x);
Otherwise derivada would be a symbolic variable and derivada(x(i)) would be an attempt to index that variable at index x(i). You cannot pass a value to a symbolic expression using (VALUE) notation.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!