- the name of the function fun is different from myfun
- fun and its gradient are both evaluated at x.

170 views (last 30 days)

Show older comments

Hi there,

I need to calculate the gradient (partial derivative) of a function. I found that Matlab has got a '.p' file/function called 'finitedifferences' to do this.

However, I am not sure how to use it. For example, I found that Matlab do it like,

[gradFd,~,~,numEvals] = finitedifferences(x,funfcn{3},[],[],[],f,[],[], ...

1:numberOfVariables,finDiffOpts,sizes,gradFd,[],[],finDiffFlags,[],varargin{:});

but what is funfcn{3} here?

Suppose I have a simple function like,

function F = myfun(x)

F = sin(x) + 3;

in which, x is a vector contains 6 elements. Then how to use the finitedifferences to get the gradient w.r.t each of this 6 elements? Thanks very much!

wbr, Aaron

Andrew Newell
on 20 May 2011

Here is an example of a function that uses gradest correctly:

function [F, g] = myfun(x)

fun = @(y) 2*sum(sin(y)) + 3;

F = fun(x);

g = gradest(fun,x);

The key differences are:

- the name of the function fun is different from myfun
- fun and its gradient are both evaluated at x.

Also, I have made it more efficient in a couple of other ways. Now you can test this directly using:

x = rand(4,1);

ganalytic = 2*cos(x)'; % This is the analytic gradient

[F,g] = myfun(x);

max(abs(g-ganalytic))

The last line tells you the maximum difference between the analytic and numerical gradients.

Andrew Newell
on 20 May 2011

That looks like an awkward way of doing it. I recommend downloading Adaptive Robust Numerical Differentiation from the FEX.

EDIT: Note that this package has functions for calculating gradient and Hessian.

Aaronne
on 20 May 2011

Arnaud Miege
on 23 May 2011

I think that's because your function myfun outputs a scalar and gradient needs a vector of values to work out what the gradient is at each point:

>> [F, g] = myfun([1 2 3 4])

F =

5.2702

g =

0

Aaronne
on 20 May 2011

Andrew Newell
on 20 May 2011

Not a problem! You already format your code nicely, which really helps.

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

Start Hunting!