Search code examples
matlabderivative

How to write a function to approximate the first partial derivatives


As stated in the title, I am trying to write a function which evaluates the partial derivative of f at a point (a,b).

However, the output of the partial derivative evaluated at (0,0) is way too large.

My supposition is that my algorithm for calculating the partial derivative is wrong. But I don't see how.

It has been a long time since I've last used MATLAB, so I do apologise if I've made some errors or used a inefficent way of writing my code.

My code is below:

function derivative = PartialDeriv(f, a, b, i)

    h = 0.0001;
    fn = zeros(1,2);

    if i == 1
        fn(i) = (f(a+h,b)-f(a,b)/h);
    elseif i==2
        fn(i) = (f(a,b+h)-f(a,b)/h);
    end

    derivative = fn(i);
end

Calling my function I get:

PartialDeriv(f, a, b, i)

where f is

f = @(x,y)(x-1).^2+(y-1).^2

I get:

f = -1.9998e+04

Doing it by hand I should get -2.

The i which is seen among the parameters for:

 PartialDeriv(f,a,b,i)

denotes my index, inorder to distinguish the partial derivative with respect to x and y.

Meaning that fn(1) is the partial derivative with respect to x and fn(2) is the partial derivative with respect to y.


Solution

  • You've missed the parentheses in both cases.
    It should be fn(i) = (f(a+h,b)-f(a,b))/h; instead of fn(i) = (f(a+h,b)-f(a,b)/h);.

    Modifying your code a little, I believe this structure better suits your intent:

    function derivative = PartialDeriv(f, a, b)
        h = 0.0001;
        derivative = zeros(1,2);
        derivative(1) = (f(a+h,b)-f(a,b))/h;
        derivative(2) = (f(a,b+h)-f(a,b))/h;
    end