If I want to calculate derivatives at a point using finite difference method, how to set rhs in Matlab so it computes correctly?

37 Views Asked by At

This question involves Matlab code, but is more about mathematics, so I post it here.

My code that calculates derivatives at a given point using finite difference method doesn't work and I think it's got something to do with rhs which I have given as rhs = [0;0;0;0;0;0] but previously I put it as rhs = [0;1;0;0;0;0] and it was even worse, because at least with all zeros I get the first dot correctly on the differentiated functions' graph.

Here is the picture that demostrates the problem:

The graph

function script()

I don't quite get what does rhs represent here and how to know the right values to it.

Here is my code:

syms x; f=tan(x^3) - x^2 + 1; h = 1;

xx=0:1/5:1;

yy = subs(f,xx);

ss=zeros(6,1);
rhs = [0;0;0;0;0;0];

l = 0;
r = 5;
 for j=0:l+r
        V(j+1,:)=[-l:r].^j;
    end
atr=V\rhs;

 for k=1:6
    ss(1)=ss(1)+atr(k)*yy(k)/h; 
 end

  l=1;r=4;   
    for j=0:l+r
        V(j+1,:)=[-l:r].^j;
    end
    atr=V\rhs; 

    for k=1:6
    ss(2)=ss(2)+atr(k)*yy(k)/h; 
    end

     l=2;r=3;

    for j=0:l+r
        V(j+1,:)=[-l:r].^j; 
    end
    atr=V\rhs; 

    for k=1:6
    ss(3)=ss(3)+atr(k)*yy(k)/h; 
    end

       l=3;r=2;

    for j=0:l+r
        V(j+1,:)=[-l:r].^j; 
    end
    atr=V\rhs; 


for k=1:6
    ss(4)=ss(4)+atr(k)*yy(k)/h;
    end

       l=4;r=1;

    for j=0:l+r
        V(j+1,:)=[-l:r].^j; 
    end
    atr=V\rhs; 

    for k=1:6
    ss(5)=ss(5)+atr(k)*yy(k)/h; 
    end

       l=5;r=0;

    for j=0:l+r
        V(j+1,:)=[-l:r].^j; 
    end
    atr=V\rhs; 

    for k=1:6
    ss(6)=ss(6)+atr(k)*yy(k)/h; 
    end

ss
subs(diff(f),xx)
    figure
    ezplot(diff(f),[-1, 1])
    hold on
    plot(xx,ss, '*')