R : Copyright 2005, The R Foundation for Statistical Computing Version 2.1.1 (2005-06-20), ISBN 3-900051-07-0 R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors. Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for a HTML browser interface to help. Type 'q()' to quit R. [Previously saved workspace restored] > # sweepex.r J F Monahan September 2007 > # > # sweep operator -- function and example > # > A <- matrix( c(3,1,0,1,4,2,0,2,6), 3, 3) > # write it out > A [,1] [,2] [,3] [1,] 3 1 0 [2,] 1 4 2 [3,] 0 2 6 > # define function > regsweep <- function(A,k) { + d <- A[k,k] # sweep out row k, col k + A[k,] <- A[k,]/d + b <- A[,k] + b[k] <- 0 # don't change row k here + A <- A - outer(b,A[k,]) # main operation + A[,k] <- -b/d # fix col k + A[k,k] <- 1/d # diagonal element & done + regsweep <- A } > # > # write it out > A <- regsweep(A,2) # sweep second row/col > A [,1] [,2] [,3] [1,] 2.75 -0.25 -0.5 [2,] 0.25 0.25 0.5 [3,] -0.50 -0.50 5.0 > A <- regsweep(A,3) # sweep third row/col > A [,1] [,2] [,3] [1,] 2.7 -0.3 0.1 [2,] 0.3 0.3 -0.1 [3,] -0.1 -0.1 0.2 > A <- regsweep(A,2) # sweep second row/col > A [,1] [,2] [,3] [1,] 3 1.0000000 0.0000000 [2,] 1 3.3333333 -0.3333333 [3,] 0 0.3333333 0.1666667 > A <- regsweep(A,1) # sweep first row/col > A [,1] [,2] [,3] [1,] 0.3333333 0.3333333 0.0000000 [2,] -0.3333333 3.0000000 -0.3333333 [3,] 0.0000000 0.3333333 0.1666667 > rm(list=ls()) # clean up >