JaneDoe
JaneDoe

Reputation: 107

First derivative in matlab

I want to calculate the first derivative of a function with matlab. However, I do not know the function's formula, I only have access to its inputs and outputs. For instance:

f([1 2 3 4 5]) = [1 4 9 16 25]; %Square function for the example

I am not satisfied of the output of:

diff([1 2 3 4 5]) %Which is [3 5 7 9]

I have seen on this forum that I am not the only one trying to calculate the first derivative of a function with matlab. But since, I don't know the mathematical formula of my function, I can't use the symbolic Math Toolbox.

So my questions are:

Thank you for your help.

Upvotes: 0

Views: 1711

Answers (2)

Matt
Matt

Reputation: 2802

To solve your problem as described I would use a combination of polyfit and polyval with a brute force approach. Something like this.

in = [1 2 3 4 5];
out = fun(in); % in this case, simply y = x.^2 
epsilon = 0.000001;
test = inf;
best = 0;
% some large term count
test = inf;
best = 0;
for n = 0:7
    p = polyfit(in, out, n);
    val = sqrt(sumsqr(polyval(p, in) - out));
    if ((val < test) & (abs(val - test) > epsilon))
        best = n;
        test = val;
    end
end
p = polyfit(in, out, best);
syms x, f;
expo = best:-1:0;
f = p * (x.^expo).';

Then you can use symbolic math on the variable f. For the example you provided this returns a polynomial dominated by x^2.

However, it seems like the better approach would be to use either the definition of the derivative or more robust numerical methods then a simple difference as others have suggested.

Upvotes: 0

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Assuming you can evaluate the function easily, here is a vary simple way to estimate the derivative. (Assuming the function behaves nicely)

x = 1:5
h = 0.0001;

dir_est= (f(x)-f(x+h))/h

Note that this is very similar to the definition of the derivitive.

Upvotes: 3

Related Questions