Last active
February 28, 2021 15:41
-
-
Save JfrAziz/77d214435536dbe3dffeefe5c8550967 to your computer and use it in GitHub Desktop.
Tugas APG uhuy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vectorLength <- function(x) { | |
if(!is.vector(x)) stop("x is not a vector") | |
return(sqrt(sum(x^2))) | |
} | |
vectorAngelCos <- function(x, y){ | |
if(!is.vector(x) || !is.vector(y)) stop("x or y is not a vector") | |
if(length(x) != length(y)) stop("x and y are not the same length") | |
# cos value of vector angel of x and y is x'y/(L_x * L_y) | |
cosValue = sum(x*y)/(vectorLength(x)*vectorLength(y)) | |
return(cosValue) | |
} | |
projection <- function(x, y){ | |
if(!is.vector(x) || !is.vector(y)) stop("x or y is not a vector") | |
if(length(x) != length(y)) stop("x and y are not the same length") | |
# projection vector of x on y is (x'y)*y/L_y^2 | |
vector = sum(x*y)*y/vectorLength(y)^2 | |
# projection lenght of x on y is L_x*cos(angel of x and y) | |
length = vectorLength(x)*abs(vectorAngelCos(x, y)) | |
return(list("vector" = vector, "length" = length)) | |
} | |
deviationVector <- function(x){ | |
if(!is.vector(x)) stop("x is not a vector") | |
return(x-mean(x)) | |
} | |
deviationMatrix <- function(x){ | |
if(!is.matrix(x)) stop("x is not a matrix") | |
avg = apply(x, 2, mean) | |
avgMatrix = matrix(rep(avg, nrow(x)), ncol = ncol(x), byrow = TRUE) | |
return(x-avgMatrix) | |
} | |
covarianceMatrix <- function(x, method = "bias"){ | |
if(!is.matrix(x)) stop("x is not a matrix") | |
d = deviationMatrix(data) | |
biased <- switch (method, | |
"bias" = 1/nrow(x), | |
"unbias" = 1/(nrow(x)-1), | |
1 | |
) | |
return(crossprod(d)*biased) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment