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?
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$.
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.
The norm of a vector is simply the square root of the sum of each component squared.
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.
norm(c(1,1), type="2") # 1.414214 norm(c(1, 1, 1), type="2") # 1.732051
This is a trivial function to write yourself:
norm_vec <- function(x) sqrt(sum(x^2))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With