I have a question on using Matlab's gradient function. Here is sample code:
npts=100;
x1 = linspace(-10,10,npts);
x2 = linspace(-10,10,npts);
x3 = linspace(-10,10,npts);
f1 = x1.^2 + 2*x2.^2 + 2*x3.^3 + 2*x1.*x2 + 2*x2.*x3;
f2 = @(x1,x2,x3) x1^2 + 2*x2^2 + 2*x3^3 + 2*x1*x2 + 2*x2*x3;
I want to numerically compute the partial derivatives of function $f_2$:
$$ dx(i)=\frac{\partial f_2}{\partial x} \bigg |_{(x1(i),x2(i),x3(i))}\\ dy(i)=\frac{\partial f_2}{\partial y} \bigg |_{(x1(i),x2(i),x3(i))} \\ dz(i)=\frac{\partial f_2}{\partial z} \bigg |_{(x1(i),x2(i),x3(i))} $$
where $i$ goes from 1 to npts.
I also defined f1, but even after reading documentation, I could not figure out how to find gradient at given points. Any help is appreciated.
You can use Finite Differences method for that.
Have a look at How does one compute a single finite differences in Matlab efficiently?.
You'll find in my answer an efficient code to do so.