我有2个不同的文件,其中一个是输入矩阵(X),有3823 * 63个元素(3823个输入和63个特征),另一个是类向量(R),有3823 * 1要素;这些元素的值从0到9(有10个类)。
我必须为每个类计算协方差矩阵。到目前为止,我只能为具有如此多嵌套循环的每个类计算平均向量。然而,它导致我脑死亡。
还有其他简单方法吗?
我的目的有代码(感谢Sam Roberts):
xTra = importdata('optdigits.tra');
xTra = xTra(:,2:64); % first column's inputs are all zero
rTra = importdata('optdigits.tra');
rTra = rTra(:,65); % classes of the data
c = numel(unique(rTra));
for i = 1:c
rTrai = (rTra==i-1); % Get indices of the elements from the ith class
meanvect{i} = mean(xTra(rTrai,:)); % Calculate their mean
covmat{i} = cov(xTra(rTrai,:)); % Calculate their covariance
end
答案 0 :(得分:2)
这可以满足您的需求吗?
X = rand(3263,63);
R = randi(10,3263,1)-1;
numClasses = numel(unique(R));
for i = 1:numClasses
Ri = (R==i); % Get indices of the elements from the ith class
meanvect{i} = mean(X(Ri,:)); % Calculate their mean
covmat{i} = cov(X(Ri,:)); % Calculate their covariance
end
此代码循环遍历每个类,选择与该类中的观察对应的R行,然后从X获取相同的行并计算它们的均值和协方差。它将它们存储在单元格数组中,因此您可以像这样访问结果:
% Display the mean vector of class 1
meanvect{1}
% Display the covariance matrix of class 2
covmat{2}
希望有所帮助!
答案 1 :(得分:1)
不要将mean
和sum
用作变量名,因为它们是有用的Matlab内置函数的名称。 (输入doc mean
或doc sum
以获取使用帮助)
同样cov
将为您计算协方差矩阵。
您可以使用逻辑索引来提取示例。
covarianceMatrices = cell(m,1);
for k=0:m-1
covarianceMatrices{k} = cov(xTra(rTra==k,:));
end
一衬垫
covarianceMatrices = arrayfun(@(k) cov(xTra(rTra==k,:)), 0:m-1, 'UniformOutput', false);
答案 2 :(得分:0)
首先为每个类构建数据矩阵。 第二,计算每个数据矩阵的协方差。
以下代码执行此操作。
% assume allData contains all the data you've read in, each row is one data point
% assume classVector contains the class of each data point
numClasses = 10;
data = cell(10,1); %use cells to store each of the data matrices
covariance = cell(10,1); %store each of the class covariance matrices
[numData dummy] = size(allData);
%get the data out of allData and into each class' data matrix
%there is probably a nice matrix way to do this, but this is hopefully clearer
for i = 1:numData
currentClass = classVector(i) + 1; %Matlab indexes from 1
currentData = allData(i,:);
data{currentClass} = [data{currentClass}; currentData];
end
%calculate the covariance matrix for each class
for i = 1:numClasses
covariance{i} = cov(data{i});
end