# How can I use Automatic differentiation tools to specify gradient to fsolve?

2 次查看（过去 30 天）
Dhruv Thakkar 2023-5-15

I have a nonlinear ODE system. I intend on using an iterative solver to calculate the steady-state(SS) solution of the system. I am aware that I can just wait for the ODE to settle to the steady-state value but that would take much longer as I need to calculate the SS response for few hundred conditions.
Currently I am using fsolve to find the root of the ODE function. However, it takes too long to estimate the Jacobian using the finite difference method. A MWE of my implementation is as follows,
classdef myClass < handle
properties
someProperty = [];
end
methods
% Some preprocesssing
options = optimoptions('fsolve','Algorithm','trust-region-dogleg','Display','off');
[tOut, x] = fsolve(@(x)self.myODE(x,inp),xInit,options);
end
end
methods (Access = private)
function [dXdt] = myODE(self,x,inp)
% Some output
dXdt = []; % Array of n x 1; n being number of equations
end
end
end
The problem that I face now is that for each iteration fsolve has to compute the Jacobian using finite differences. It is not possible to get an analytical expression of the Jacobian, so I was thinking of using AD to calculate the jacobian at each point. I found dlgradient as the implementation of AD in matlab. However, it works with dlarray. Some functions that I am using don't support dlarray.
How can I make this work? Any help is appreciated.
Thank you very much.

### 回答（1 个）

Ranjeet 2023-5-29
As per my understanding, there is data incompatibility issue while using some functions. It is suggested to first convert the 'dlarray' type data to 'matrix' and then use with the functions not accepting 'dlarray' as input.
You may use the 'extractdata' method to get the underlying data from 'dlarray' to a 'matrix' type.
The following MATLAB answer can also be referred -
##### 1 个评论显示 -1更早的评论隐藏 -1更早的评论
Dhruv Thakkar 2023-5-29
Hi Ranjeet, I have already tried 'extractdata' for this. But I still run into errors and I seems I am adding the overhead to convert the data. Is there a more efficient way to provide the gradients?

### 类别

Help CenterFile Exchange 中查找有关 Solver Outputs and Iterative Display 的更多信息

R2022a

### Community Treasure Hunt

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

Start Hunting!