Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[CV] within-class and between-class covariance matrix
function [withincovar, betweencovar] = discriminativecov(X, ids)
arr_ids = int16(ids);
dim = size(X, 2);
num_pts = size(X, 1);
num_class = size(unique(arr_ids), 1);
arr_ids_sets = cell(num_class,1);
arr_ids_count = zeros(num_class,1);
for i = 1:num_class
arr_ids_sets{i} = find(arr_ids == i);
arr_ids_count(i) = length(arr_ids_sets{i});
end
%% Mean of each class
arr_mean = zeros(num_class, dim);
for i = 1:num_class
arr_mean(i,:) = mean(X(arr_ids_sets{i},:));
end
%% Mean overall
overall_mean = mean(X);
%% Between class covariance matrix
betweencovar = zeros(dim, dim);
for i=1:num_class
diff = arr_mean(i,:) - overall_mean;
betweencovar = betweencovar + arr_ids_count(i) * diff'*diff;
end
betweencovar = betweencovar ./ (num_pts - 1);
withincovar = zeros(dim, dim);
for i=1:num_class
normalized_class = bsxfun(@minus, X(arr_ids_sets{i},:), arr_mean(i,:));
withincovar = withincovar + normalized_class'*normalized_class;
end
withincovar = withincovar ./ (num_pts - 1);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment