dlgradient of a subset of variables
Show older comments
I would like to apply dlgradient to a parametrized function, which would allow me in some cases to get the complete gradient of the function, but in others would take only the derivative with respect to the i-th variable. My attempt below fails. Is there a way that both succeeds and which would be efficient in the more general case when numel(x0) is large?
x0 = dlarray( [1; 2] );
i=[];
y_grad=dlfeval(@(x)oneDeriv(x,i), x0) %works
i=2;
dy_dxi=dlfeval(@(x)oneDeriv(x,i), x0) %fails
function out = oneDeriv(x,i)
y=sum(x.^2)/2;
if isempty(i) %take complete gradient
out=dlgradient(y,x);
else %take gradient only w.r.t x(i)
out=dlgradient(y,x(i));
end
end
Accepted Answer
More Answers (1)
Ben
on 13 Feb 2024
2 votes
This is a subtle part of the dlarray autodiff system, the line dlgradient(y,x(i)) returns 0 because it sees the operation x -> x(i), and only knows that y depends on x, not x(i).
You can work around this by computing all the derivatives and do indexing afterwards:
function out = oneDeriv(x,i)
y = sum(x.^2)/2;
out = dlgradient(y,x);
if ~isempty(i)
out = out(i);
end
end
1 Comment
Categories
Find more on Parallel and Cloud in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!