0

This is my code in R to run Gauss Elimination:

mat <- matrix(c(8,-2,5,-1,4,8,5,15,2,-2,10,-12),nrow = 3, ncol = 4, byrow = TRUE)
n = nrow(mat)
print(mat)
print(n)
for (k in 1:n-1){
  print(k)
  for (i in k+1:n){
    mat[i,k] <- mat[i,k] / mat[k,k]
    for (j in k+1:n-1){
      mat[i,j] <- mat[i,j] - mat[i,k] * mat[k,j]
    }
    print(mat)
  }
}

The k first value is 0 instead of 1. What is wrong?

  • `:` has higher operator precedence than `+` or `-` (add and subtract), see https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html – ThomasIsCoding Jul 09 '20 at 12:07

1 Answers1

1

This is because the : operator is more tightly bound than the arithmetic operators, so for(k in 1:n-1) means for(k in (1:n) - 1) which is the same as for(k in 0:(n-1)). I think you intended for(k in 1:(n-1)).

You make the same mistake in your other for loops. You must add the parentheses to make them work:

mat <- matrix(c(8,-2,5,-1,4,8,5,15,2,-2,10,-12),nrow = 3, ncol = 4, byrow = TRUE)
n = nrow(mat)
print(mat)
#>      [,1] [,2] [,3] [,4]
#> [1,]    8   -2    5   -1
#> [2,]    4    8    5   15
#> [3,]    2   -2   10  -12
print(n)
#> [1] 3
for (k in 1:(n-1)){
  print(k)
  for (i in (k+1):n){
    mat[i,k] <- mat[i,k] / mat[k,k]
    for (j in (k+1):(n-1)){
      mat[i,j] <- mat[i,j] - mat[i,k] * mat[k,j]
    }
    print(mat)
  }
}
#> [1] 1
#>      [,1] [,2] [,3] [,4]
#> [1,]  8.0   -2    5   -1
#> [2,]  0.5    9    5   15
#> [3,]  2.0   -2   10  -12
#>      [,1] [,2] [,3] [,4]
#> [1,] 8.00 -2.0    5   -1
#> [2,] 0.50  9.0    5   15
#> [3,] 0.25 -1.5   10  -12
#> [1] 2
#>      [,1]      [,2]     [,3] [,4]
#> [1,] 8.00 -2.000000  5.00000   -1
#> [2,] 0.50  9.000000  5.00000   15
#> [3,] 0.25  1.333333 10.83333  -12

Created on 2020-07-09 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87