Forward difference gradient vector in multiple dimensions
Show older comments
If I have a function of the form
f = @(x) x.^2
then given a step-size h, I can use a forward difference given by
fd = @(x) (f(x+h)-f(x))/h
to get a rough estimate of its gradient in 1 dimension. However, if I have a 2 dimensional function of the form
f = @(x) x(1).^2 + x(2).^2
how would I go about finding the gradient vector, using forward differences of this function? The gradient for each component would be given by df/dx1 = (f(x1+h,x2)-f(x1,x2))/h and df/dx1 = (f(x1,x2+h)-f(x1,x2))/h, but unfortunately I can't seem to be able to figure out how to code this in MATLAB.
Answers (1)
Jan
on 28 Apr 2017
h = 0.005;
f = @(x) x(1).^2 + x(2).^2
dfdx1 = @(x) (f([x(1) + h, x(2)]) - f(x)) / h
dfdx2 = @(x) (f([x(1), x(2) + h]) - f(x)) / h
x = [2,3]
dfdx1(x)
dfdx2(x)
Categories
Find more on Error Handling in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!