Euclidean norm using R - r

I want to use the matlab syntax below in term of R code, actually X is a nxm matrix:
Hs(i,j)=norm(X(i,:)-X(j,:))^2;
Hs(j,i)=Hs(i,j);
Hs=exp(-Hs/3);
Here is my R code:
Hs[i,j]=sqrt(sum((X[i,]- X[j,])^2))
Hs[i,j]=Hs[j,i]
Hs=exp(-Hs/3)
But the problem the result output was matrix 3x3 with all element =1. Please help.

Here the answer:
#Euclidean matrix
euc.dist <- function(p, q) {
ed<-sqrt(sum((p - q)^2))
return((ed))
}
#Gaussian kernel nxn matrix
get.gramm.nn <- function(X) {
n <- dim(X)[1]
Gramm<- matrix(0, n, n) #initializes Gramm array #i=index for rows
#j=index for columns Gramm<-as.matrix(Gramm) # Gramm matrix
for (i in 1:n) {
for (j in 1:n) {
Gramm[i, j] <- euc.dist(X[i,], X[j,])
}
}
Gramm<- exp(-(Gramm)^2)
return(Gramm)
}

Related

How to change colsums and sum to loop in a formula?

I have a vector named y which has n numerical elements and a matrix n*n named w where its elements are numbers. I want to use the below formula for the above data:
I have written the following code in R using functions colSums and sum:
dy<-y-mean(y)
n*(y-mean(y))*colSums(w*dy)/sum(dy^2)#=local[,1]
Now, I want to change my above code to write it with for loop (without using colSums and sum). Indeed, I want to make the formula using for loop instead of using colSums and sum.
Thank you in advance for your help.
I don't know why you want to use a for-loop since in this case there are many disadvantages, but here we go.
First we calculate the donominator:
dy_square_sum <- 0
for (i in seq_along(y)) {
dy_square_sum <- dy_square_sum + dy[i]^2
}
In the next step, we calculate the enumerator and build up your desired output:
weighted_sum <- rep(0,n)
output <- rep(0, n)
for (i in seq_along(y)) {
for (j in seq_along(y)) {
weighted_sum[i] <- weighted_sum[i] + w[j,i] * dy[j]
}
output[i] <- n * dy[i] / dy_square_sum * weighted_sum[i]
}
or a little simplified but less efficient
output <- rep(0, n)
for (i in seq_along(y)) {
for (j in seq_along(y)) {
output[i] <- output[i] + n * dy[i] * w[j,i] * dy[j] / dy_square_sum
}
}

Converting nested summation to R type matrix multiplication

I am trying to implement a nested summation in R. The for loop implementation is:
sum = 0
for(i in 1:n){
for(j in 1:n){
for(k in 1:n){
sum = sum + w[i,j]*w[j,k]
}
}
}
where w is a symmetric square matrix and n is the number of rows (or columns).
Please see the formula I am trying to implement. (SO did not allow me to write Latex nor add the image here.)
The nested for loops above takes forever. How do I implement this efficiently the R way?
Try this:
Sum2 <- sum(w %*% w)
all.equal(Sum, Sum2)
## [1] TRUE
Note
We used for comparison:
# input
set.seed(123)
n <- 5
w <- matrix(rnorm(n^2), n)
# from question
Sum = 0
for(i in 1:n){
for(j in 1:n){
for(k in 1:n){
Sum = Sum + w[i,j]*w[j,k]
}
}
}

Is there an efficient way to write the code snippet without for loops in R?

Is there an efficient way to write the below code in R?
v is a matrix of length n x n.
k <- matrix(0, n, n-2)
for (i in seq(n)){
for (j in seq(n-2)) {
k[i,j] = v[i, j]
}
}

Calculate "matrix of cofactors" in R?

Is there any way to calculate the matrix of cofactors in R directly?
(Without multiplying it by determinant!)
http://en.wikipedia.org/wiki/Minor_(linear_algebra)#Matrix_of_cofactors
Build your own function:
library(functional)
M<-matrix(1:9,3,3)
getCofactor = function(M, i, j)
{
stopifnot(length(unique(dim(M)))==1)
stopifnot(all(c(i,j)<=dim(M)))
det(M[-i,-j])*(-1)^(i+j)
}
grid = expand.grid(1:dim(M)[1], 1:dim(M)[2])
matrix(mapply(Curry(getCofactor, M=M), grid$Var1, grid$Var2), nrow=dim(M)[1])
You can write a function that gives you the whole matrix of cofactors with one click.
getCofactors <- function(M) {
stopifnot(length(unique(dim(M)))==1) # Check if Matrix = Square
cf <- M # creating a Matrix that has the same Dimensions as M
for(i in 1:dim(M)[1]){
for(j in 1:dim(M)[2]){
cf[i,j] <- (det(M[-i,-j])*(-1)^(i+j)) # overwriting the Values of cf Matrix with cofactors
}
}
return(cf) # output of cofactors matrix
}
If you Want you can save your function and load it on demand:
dump("getCofactors", file="getCofactors.R")
source("getCofactors.R")

R: Generate matrix from function

In R I'm interested in the general case to generate a matrix from a formula such as:
X = some other matrix
Y(i, j) = X(i, j) + Y(i - 1, j - 1)
Unfortunately I can't find how to account for the matrix self-referencing.
Obviously order of execution and bounds checking are factors here, but I imagine these could be accounted for by the matrix orientation and formula respetively.
Thanks.
This solution assumes that you want Y[1,n] == X[1,n] and Y[n,1] == X[n,1]. If not, you can apply the same solution on the sub-matrix X[-1,-1] to fill in the values of Y[-1,-1]. It also assumes that the input matrix is square.
We use the fact that Y[N,N] = X[N,N] + X[N-1, N-1] + ... + X[1,1] plus similar relations for off-diagonal elements. Note that off-diagonal elements are a diagonal of a particular sub-matrix.
# Example input
X <- matrix(1:16, ncol=4)
Y <- matrix(0, ncol=ncol(X), nrow=nrow(X))
diag(Y) <- cumsum(diag(X))
Y[1,ncol(X)] <- X[1,ncol(X)]
Y[nrow(X),1] <- X[nrow(X),1]
for (i in 1:(nrow(X)-2)) {
ind <- seq(i)
diag(Y[-ind,]) <- cumsum(diag(X[-ind,])) # lower triangle
diag(Y[,-ind]) <- cumsum(diag(X[,-ind])) # upper triangle
}
Well, you can always use a for loop:
Y <- matrix(0, ncol=3, nrow=3)
#boundary values:
Y[1,] <- 1
Y[,1] <- 2
X <- matrix(1:9, ncol=3)
for (i in 2:nrow(Y)) {
for (j in 2:ncol(Y)) {
Y[i, j] <- X[i, j] + Y[i-1, j-1]
}
}
If that is too slow you can translate it to C++ (using Rcpp) easily.

Resources