Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate the Euclidean norm of a vector in R?

I tried norm, but I think it gives the wrong result. (the norm of c(1, 2, 3) is sqrt(1*1+2*2+3*3), but it returns 6..

x1 <- 1:3 norm(x1) # Error in norm(x1) : 'A' must be a numeric matrix norm(as.matrix(x1)) # [1] 6 as.matrix(x1) #      [,1] # [1,]    1 # [2,]    2 # [3,]    3 norm(as.matrix(x1)) # [1] 6 

Does anyone know what's the function to calculate the norm of a vector in R?

like image 671
Hanfei Sun Avatar asked Jun 07 '12 14:06

Hanfei Sun


People also ask

What does norm () do in R?

Norm returns a scalar that gives some measure of the magnitude of the elements of x . It is called the $p$-norm for values $-Inf \le p \le Inf$, defining Hilbert spaces on $R^n$.

How do you find the Euclidean length of a vector?

The length of a vector is most commonly measured by the "square root of the sum of the squares of the elements," also known as the Euclidean norm. It is called the 2-norm because it is a member of a class of norms known as p -norms, discussed in the next unit.

How do you find the norm of a vector?

The norm of a vector is simply the square root of the sum of each component squared.

Is Euclidean norm the same as 2-norm?

The L2 norm calculates the distance of the vector coordinate from the origin of the vector space. As such, it is also known as the Euclidean norm as it is calculated as the Euclidean distance from the origin.


2 Answers

norm(c(1,1), type="2")     # 1.414214 norm(c(1, 1, 1), type="2")  # 1.732051 
like image 128
Bernd Elkemann Avatar answered Sep 20 '22 11:09

Bernd Elkemann


This is a trivial function to write yourself:

norm_vec <- function(x) sqrt(sum(x^2)) 
like image 45
joran Avatar answered Sep 21 '22 11:09

joran