R矩阵的欧几里德范数

时间:2015-03-29 03:01:50

标签: r matrix norm

我有一个自然语言处理课程的数据矩阵,我需要Euclidean规范化矩阵,我对R很新,所以我无法弄清楚我的代码出错了什么,继承人代码:

A=matrix(
c(1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,0,1,2,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1), 
nrow=11,
ncol=10)
norm_vec <- function(x) sqrt(sum(x^2))
B=matrix(
nrow=11,
ncol=10)
for(n in 1:10)
length <- norm_vec(A[,n])
for(j in 1:11)
B[j,n]<- A[j,n]/length

为此,我得到的输出只有最后一列是正确的,其他列是NA,我不明白为什么会这样。我做错了什么?

2 个答案:

答案 0 :(得分:2)

@ Sathish的解决方案可以完全矢量化

 A / matrix(sqrt(colSums(A*A)), nrow=11, ncol=10, byrow=TRUE)

 #          [,1] [,2]      [,3]      [,4]      [,5]      [,6]      [,7]      [,8]      [,9]     [,10]
 #[1,] 0.5773503  0.0 0.0000000 0.4082483 0.5773503 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
 #[2,] 0.5773503  0.5 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
 #[3,] 0.5773503  0.5 0.5773503 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
 #[4,] 0.0000000  0.5 0.0000000 0.4082483 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
 #[5,] 0.0000000  0.5 0.0000000 0.8164966 0.5773503 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
 #[6,] 0.0000000  0.0 0.5773503 0.0000000 0.5773503 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000
 #[7,] 0.0000000  0.0 0.5773503 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.7071068
 #[8,] 0.0000000  0.0 0.0000000 0.0000000 0.0000000 0.7071068 0.0000000 0.0000000 0.0000000 0.0000000
 #[9,] 0.0000000  0.0 0.0000000 0.0000000 0.0000000 0.7071068 0.7071068 0.5773503 0.7071068 0.0000000
 #[10,] 0.0000000  0.0 0.0000000 0.0000000 0.0000000 0.0000000 0.7071068 0.5773503 0.0000000 0.0000000
#[11,] 0.0000000  0.0 0.0000000 0.0000000 0.0000000 0.0000000 0.0000000 0.5773503 0.7071068 0.7071068

答案 1 :(得分:0)

A=matrix(c(1,1,1,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,0,1,2,0,0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,1), nrow=11,  ncol=10)

norm_vec <- function(x){ 
                 sqrt(sum(x^2))
            }

B=matrix(nrow=11, ncol=10)

Euc.lenA <- c()

for(n in 1:10){ 
   Euc.lenA <- c(Euc.lenA, norm_vec(A[,n]))
}

for(j in 1:10){
   B[,j]<- A[,j]/Euc.lenA[j]
}

Euc.lenA
[1] 1.732051 2.000000 1.732051 2.449490 1.732051 1.414214 1.414214 1.732051 1.414214 1.414214

A and B