I have a kernel matrix which looks as follows:
kern <- matrix(c(1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,1), dimnames=list(c("r1", "r1", "r3"), c("c1a", "c1b", "c2a", "c2b", "c3a", "c3b")), ncol=6, nrow=3)
> kern
c1a c1b c2a c2b c3a c3b
r1 1 1 0 0 0 0
r2 0 0 1 1 0 0
r3 0 0 1 1 1 1
Now I want to apply row operations such that kern[,c("c1b", "c2b", "c3b")]
is the identity matrix. I know that this is easily accomplished by substracting the second row from the third:
kern[3,] = kern[3,] - kern[2,]
,
but is there a function in R which does that for me? A function for the reduced row echelon form posted in another thread isn't what I need.
EDIT
I have a clumsy solution
sub <- kern[,c("c1b", "c2b", "c3b")]
for (i in which(colnames(kern) %in% colnames(sub))){
##identify which columns have more than one entry
nonzero.row.idx <- which(kern[,i] != 0)
while(length(nonzero.row.idx) > 1){
row.combinations <- combn(nonzero.row.idx, 2)
for (j in ncol(row.combinations)){
r1.idx <- row.combinations[1,j]
r2.idx <- row.combinations[2,j]
r1 <- kern[r1.idx,]
r2 <- kern[r2.idx,]
if (min(r1 - r2) >=0)
kern[r1.idx, ] <- r1-r2
else if (min(r2 - r1) >=0)
kern[r2.idx, ] <- r2-r1
else
stop("Producing negative entries in row")
nonzero.row.idx <- which(kern[,i] != 0)
}
}
}
kern[,c("c1b", "c2b", "c3b")]
Also I forgot to mention that I do not want any entry in kern
to be negative. This code works for my few examples, however, it is prone to cause trouble for many other matrices.
Yiour assignment arrow is directed in the wrong direction.
kern <- matrix(c(1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,1),
dimnames=list(c("r1", "r1", "r3"),
c("c1a", "c1b", "c2a", "c2b", "c3a", "c3b")),
ncol=6, nrow=3)
sub <- kern[,c("c1b", "c2b", "c3b")]
You can attempt to replicate what your brain (or at least mine) did when asked to find the correct row to subtract from a row that had an off-axis non-zero entry:
id <- which( sub != 0 & row(sub) != col(sub), arr.ind=TRUE)
id
# row col
#r3 3 2
> sub[ id[ ,"row" ], ] <- sub[id[ ,"row" ] , ] - sub[id[, "col" ], ]
> sub
c1b c2b c3b
r1 1 0 0
r1 0 1 0
r3 0 0 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.