dlgradient: covariance matrix derivative.

9 views (last 30 days)
MA
MA on 13 Dec 2021
Answered: MA on 16 Dec 2021
Assuming I have a matrix x of size (mxn), the covariance matrix is of the size nxn. I want to find the gradient of the covariance matrix with respect to the input. So, starting with this code:
function [y,dx]=cov_der(x)
y=x'*x;
dx=dlgradient(y,x,'EnableHigherDerivatives',true);
end
and evaluating it as:
[y,dx]=dlfeval(@cov_der,x)
This does not work for matrices but it works for scalars. So, is there anyway I could find the gradient with respect to every element in the matrix. THanks.

Accepted Answer

MA
MA on 16 Dec 2021
I actually solve it. For anyone looking for the same problem:
function [y,dx]=cov_der(x)
%simple example
%x=dlarray(and(3,3));
%[y,dx]=dlfeval(@cov_der,x)
y=zeros(size(x,2),size(x,2));
z=size(x,1);
y=dlarray(y);
for i=1:size(x,2)
for j=1:size(x,2)
y(i,j)=sum(x(:,i).*x(:,j))./z;
end
end
dx=zeros(size(x,2)*size(x,2),size(x,1),size(x,2));
index=1;
for i=1:size(x,2)
for j=1:size(x,2)
dx(index,:,:)=dlgradient(y(i,j),x,'EnableHigherDerivatives',true);
index=index+1;
end
end
end

More Answers (1)

yanqi liu
yanqi liu on 14 Dec 2021
yes,sir,may be use loop for every element in matrix
clc; clear all; close all;
[X1, X2] = meshgrid(linspace(0,1,10));
X1 = dlarray(X1(:));
for i = 1:length(X1)
[y(i),dx(i)]=dlfeval(@cov_der, dlarray(X1(i)));
end
% figure; plot(extractdata(X1),extractdata(y))
% hold on;
% plot(extractdata(X1),extractdata(dx))
function [y,dx]=cov_der(x)
y=x'*x;
dx=dlgradient(y,x,'EnableHigherDerivatives',true);
end
  1 Comment
MA
MA on 14 Dec 2021
THanks for your answer, but in this example you gave the covariance is calculated for each point. I want to calculate the covariance matrix for a matrix of size mxn so the output (y) will be of size nxn.

Sign in to comment.

Categories

Find more on Deep Learning Toolbox 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!