How can i call an equation and it's derivative inside a matlab function?

조회 수: 8 (최근 30일)
As a newbie, i like to ask a simple question. I am trying to impliment a newton-rapson method for a simple equation as an example. I create a different matlab function from main function for the equation and call it inside the main function. However when I try to call the functions derivative it gives an error. I am aimin to not to take the derivative inside the main function for optimization concerns. I did try different methods but they give errors all the same.
function nr(x0,TC)
% TC is given in terms of percentage!
if nargin<2, x0=0; TC=10^-4;end
error=TC+1; i=0;
x(1)=x0;
while(error>TC)
x(i+2)=x(i+1)-f(x(i+1))/fd(x(i+1));
error=100*abs((x(i+2)-x(i+1))/x(i+2));
i=i+1;
end
fprintf('After %d iterations an approximate root is %f',i,x(i));
end
function [fx]=f(x)
fx=exp(-x)-x;
end
function fd=fd(x)
% syms x %These parts where i need help.
% fx=exp(-x)-x;
% fd=matlabFunction(diff(fx))
fd=-exp(-x)-1;
end

채택된 답변

Ömer Utku Örengül
Ömer Utku Örengül 2021년 11월 8일
편집: Ömer Utku Örengül 2021년 11월 8일
So I have it worked like this.
function fd=fd(a)
syms a
fx=exp(-a)-a;
fd=diff(fx);
end
and put "syms a" at the main function and finally changed "fd(x(i+1))" with;
...
x(i+2)=x(i+1)-f(x(i+1))/subs(fd,a,x(i+1)); % subs(fd,a,x(i+1))
...
It worked as intended.

추가 답변 (1개)

Alan Stevens
Alan Stevens 2021년 11월 7일
Like this, perhaps:
% TC is given in terms of percentage!
x0=0; TC=10^-4;
error=TC+1; i=0;
x(1)=x0;
while(error>TC)
[fx, fd] = f(x(i+1));
x(i+2)=x(i+1)-fx/fd;
error=100*abs((x(i+2)-x(i+1))/x(i+2));
i=i+1;
end
fprintf('After %d iterations an approximate root is %f',i,x(i));
After 4 iterations an approximate root is 0.567143
function [fx, fd]=f(x)
fx=exp(-x)-x;
fd = -exp(-x)-1;
end
  댓글 수: 3
Walter Roberson
Walter Roberson 2021년 11월 7일
편집: Walter Roberson 2021년 11월 8일
There are two notable diff() functions. One of them only applies if the first parameter is symbolic or symbolic function.
syms x
fd = matlabFunction(diff(f(x),x))
fd = function_handle with value:
@(x)-exp(-x)-1.0
function [fx]=f(x)
fx=exp(-x)-x;
end
Alan Stevens
Alan Stevens 2021년 11월 8일
편집: Alan Stevens 2021년 11월 8일
You could always try something like this:
% TC is given in terms of percentage!
fx = @(x) exp(-x)-x;
dx = 10^-10; % Choose a suitably small value
fd = @(x) (fx(x+dx) - fx(x))/dx;
x0=0; TC=10^-4;
error=TC+1; i=0;
x(1)=x0;
while(error>TC)
x(i+2)=x(i+1)-fx(x(i+1))/fd(x(i+1));
error=100*abs((x(i+2)-x(i+1))/x(i+2));
i=i+1;
end
fprintf('After %d iterations an approximate root is %f',i,x(i));
After 4 iterations an approximate root is 0.567143
but, if you have the Symbolic Maths package, Walter's suggestion is best.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Number Theory에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by