How to fine numerical gradient
Show older comments
I have a function f(x,y). Following is just a sample function explaining how I save f(x,y) value in a 2D array.
clear; clc;
xs = linspace(1,2,100);
ys = linspace(1,3,100);
fun_values = zeros(100,100);
for ix = 1:100
x = xs(ix);
for iy = 1:100
y = ys(iy);
fun_values(ix,iy) = x^2+y^2;
end
end
I want to calculate
and
. I am confused what is the correct way to use gradient() function given the way how I store values in fun_values variable.
and
. I am confused what is the correct way to use gradient() function given the way how I store values in fun_values variable.Accepted Answer
More Answers (1)
There is another way to find the numerical gradient for the given function
clear; clc;
xs = linspace(1,2,100);
ys = linspace(1,3,100)'; % transpose here
fun_values = zeros(100,100);
[Xs, Ys] = meshgrid(xs,ys);
% Try use array operation instead of loops
fun_values = Xs.^2 + Ys.^2;
% Gradient
[Fx, Fy] = gradient(fun_values)
1 Comment
Luqman Saleem
on 21 Mar 2024
Categories
Find more on Numerical Integration and Differentiation 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!