How to fine numerical gradient
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Luqman Saleem
am 20 Mär. 2024
Kommentiert: Luqman Saleem
am 21 Mär. 2024
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.
0 Kommentare
Akzeptierte Antwort
Chunru
am 21 Mär. 2024
clear; clc;
xs = linspace(1,2,100);
ys = linspace(1,3,100)'; % transpose here
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
%}
% Try use array operation instead of loops
fun_values = xs.^2 + ys.^2;
% Gradient
[Fx, Fy] = gradient(fun_values, xs, ys);
Weitere Antworten (1)
VBBV
am 21 Mär. 2024
Bearbeitet: VBBV
am 21 Mär. 2024
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)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!