Matlab不同类的协方差矩阵计算
我有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
I've got 2 different files, one of them is an input matrix (X) which has 3823*63 elements (3823 input and 63 features), the other one is a class vector (R) which has 3823*1 elements; those elements have values from 0 to 9 (there are 10 classes).
I have to compute covariance matrices for every classes. So far, i could only compute mean vectors for every classes with so many nested loops. However, it leads me to brain dead.
Is there any other easy way?
There is the code for my purpose (thanks to 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这能满足您的需要吗?
此代码循环遍历每个类,选择 R 中与该类的观测值相对应的行,然后从 X 中获取相同的行并计算它们的均值和协方差。它将它们存储在元胞数组中,因此您可以像这样访问结果:
希望有帮助!
Does this do what you need?
This code loops through each of the classes, selects the rows of R that correspond to observations from that class, and then gets the same rows from X and calculates their mean and covariance. It stores them in a cell array, so you can access the results like this:
Hope that helps!
不要使用
mean
和sum
作为变量名称,因为它们是有用的 Matlab 内置函数的名称。 (输入docmean
或docsum
以获得使用帮助)此外
cov
将为您计算协方差矩阵。您可以使用逻辑索引来提取示例。
单线
Don't use
mean
andsum
as a variable names because they are names of useful Matlab built-in functions. (Typedoc mean
ordoc sum
for usage help)Also
cov
will calculate the covariance matrix for you.You can use logical indexing to pull out the examples.
One-liner
首先构建每个类的数据矩阵。
其次计算每个数据矩阵的协方差。
下面的代码执行此操作。
First construct the data matrix for each class.
Second compute the covariance for each data matrix.
The code below does this.