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?
3 views (last 30 days)
Show older comments
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 Comments
Torsten
on 1 May 2025
Edited: Torsten
on 1 May 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).
Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!