This seems to work:
X0 = dlarray( [1; 2; 3; 4]*10 );
subset=[2,3];
gradTotal = getGradient(X0) %total gradient
gradTotal =
4×1 dlarray
10
20
30
40
gradSubset = getGradient(X0,2:3) %gradient on subset of x
gradSubset =
2×1 dlarray
20
30
function grad = getGradient(Xall,subset)
if nargin<2, subset=':'; end
grad = dlfeval( @(xsub)theFunction(X,xsub,subset), Xall(subset));
end
function grad = theFunction(Xall,xsub,subset)
Xall(subset)=xsub;
y=sum(Xall.^2)/2;
grad=dlgradient(y,xsub);
end