下午好!
在R下,我开发了以下代码:
X
k=10
w_k=rep(1,k)/k
n_j=rep(0,k)
print(w_k)
data=as.matrix(iris[1:150,-5])
means=sample(1:dim(data)[1],k,replace=FALSE)
mu=as.matrix(iris[means,-5])
sigma=cov(data)
sigma_list=rep(list(sigma),k)
P_Cj_Xi<-function(Xi,mu,sigma_list=sigma_list){
k=length(Xi)
n_j=rep(0,k)
r=lapply(1:k, function(i) r[i]=solve(matrix(unlist(sigma_list[i]),ncol=k)))
# lapply isn't storing the solve(matrix(unlist(sigma_list[i]),ncol=k)) from 1 to k
# try print(solve(matrix(unlist(sigma_list[i]),ncol=k))) , the inverse
# is correctly computed. I need to access each of inverses .
}
# example of run :
P_Cj_Xi(Xi=data[1,],mu,sigma_list=sigma_list)
是一个包含sigma_list
矩阵的列表。所有这些矩阵最初都等于k=10
。我需要遍历sigma=cov(data)
并计算此列表中每个矩阵的逆。那些计算出的逆矩阵应存储在另一个列表sigma_list
中。
使用前面的代码,我通常会收到此错误:
r
我希望我的问题清楚。预先感谢您的帮助!
答案 0 :(得分:0)
我应该使用r=matrix(NA,length(Xi),length(Xi))
创建一个空矩阵,然后可以重复r
多次=n_clusters
P_Cj_Xi<-function(Xi,mu,sigma_list=sigma_list,n_clusters=k){
k=n_clusters
n_j=rep(0,length(Xi))
r=matrix(NA,length(Xi),length(Xi))
r=rep(list(r),n_clusters )
r=lapply(1:n_clusters , function(i) r[[i]]=solve(matrix(unlist(sigma_list[i]),ncol=length(Xi))))
r
#n_j=sapply(1:k, function(i) -1/2*(Xi-mu[i])%*%r[i]%*%(t(Xi-mu[i])))
#n_j
}
P_Cj_Xi(Xi=data[1,],mu,sigma_list=sigma_list)