How to use the Finite Difference Method to get the gradient?
이전 댓글 표시
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
채택된 답변
추가 답변 (6개)
Arnaud Miege
2011년 5월 20일
1 개 추천
Arnaud
Andrew Newell
2011년 5월 20일
0 개 추천
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
2011년 5월 20일
0 개 추천
댓글 수: 3
Arnaud Miege
2011년 5월 20일
I think you need to pass a vector of values to the gradient function, I'm not sure this would work within a function:
xi = [4 2 3 4]
F = 2*sin(xi) + 3;
gradient(F)
Aaronne
2011년 5월 20일
Arnaud Miege
2011년 5월 23일
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
2011년 5월 20일
댓글 수: 3
Andrew Newell
2011년 5월 20일
Generally your questions should be added to your original question or included as comments to one of the answers. This makes it more clear what is an answer and what is not.
Aaronne
2011년 5월 20일
Andrew Newell
2011년 5월 20일
Not a problem! You already format your code nicely, which really helps.
Aaronne
2011년 5월 20일
댓글 수: 2
Andrew Newell
2011년 5월 20일
You get a recursion error because MYFUN is calling itself instead of the function F. Instead of using derivest, you should use gradest from the same package (see the edit to my answer above).
Aaronne
2011년 5월 20일
카테고리
도움말 센터 및 File Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!