How can I loop over i and j, to compute the ith row and jth column of the Jacobian matrix, using the central difference method?

5 visualizaciones (últimos 30 días)
Hi there!
I'm practicing with this toy problem and want to loop over i and j to compute the ith row and jth column of the Jacobian partial derivatives matrix, using the central difference method. The for loop that's commented out works already (it closely follows an answer posted yesterday by Matt J.), so I'm just trying to find another way to do this problem. Ideally, I want to do something like:
J(i,j) = ( zdot(i) ( X(j) + h - zdot(i) ( X(j) - h ) ) / (2*h), but I get errors from Matlab about chain indexing not being allowed.
Most natural for me would be to differentiate across, not vertically, when computing the Jacobian, so I was wondering whether I could put this into code, too.
Thanks in advance,
%% Jacobian Practice
zdot = @(z) myrhs(z);
InitialGuess = [1,1]; % pass a good initial guess to fsolve
X = fsolve(zdot,InitialGuess) % a fixed point
h = .000001; % finite-differencing step-size
% delta = speye(2);
% J = zeros(2,2);
% for i = 1:2
% J(:,i) = ( zdot( X + h*delta(:,i) ) - zdot( X - h*delta(:,i) ) ) / (2*h);
% end
for i = 1:2
for j = 1:2
J(i,j) = ( zdot( X(j) + h ) - zdot( X(j) - h) ) / (2*h);
end
end
%% write a system of two equations in two unknowns
function zdot = myrhs(z)
x = z(1);
y = z(2);
xdot = x + y^2 - pi;
ydot = x + y;
zdot = [xdot; ydot];
end
  10 comentarios
Noob
Noob el 1 de Mayo de 2025

Hi Matt!

Yes, thanks for that!

I was wondering:

How exactly does the central difference method differentiate one variable while keeping the other variables constant? When I do it with formulas it’s clear. If there are no formulas for the functions, how does that happen? Sorry for the basic question.

Thanks!

Torsten
Torsten el 1 de Mayo de 2025
Editada: Torsten el 1 de Mayo de 2025
If there are no formulas for the functions, how does that happen?
How do you want to apply central differencing if there are no formulas for the functions ?
As you can see from the central differencing formula, you must be given values for zdot in at least 4 points around X along the 2 main axes to compute an approximation for the Jacobian (and in 12 points along the 6 main axes for your ODE application).

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by