How to resolve the algorithm Gaussian elimination step by step in the R programming language

Published on 12 May 2024 09:40 PM
#R

How to resolve the algorithm Gaussian elimination step by step in the R programming language

Table of Contents

Problem Statement

Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Gaussian elimination step by step in the R programming language

Source code in the r programming language

gauss <- function(a, b) {
  n <- nrow(a)
  det <- 1

  for (i in seq_len(n - 1)) {
    j <- which.max(a[i:n, i]) + i - 1
    if (j != i) {
      a[c(i, j), i:n] <- a[c(j, i), i:n]
      b[c(i, j), ] <- b[c(j, i), ]
      det <- -det
    }

    k <- seq(i + 1, n)
    for (j in k) {
      s <- a[[j, i]] / a[[i, i]]
      a[j, k] <- a[j, k] - s * a[i, k]
      b[j, ] <- b[j, ] - s * b[i, ]
    }
  }

  for (i in seq(n, 1)) {
    if (i < n) {
      for (j in seq(i + 1, n)) {
        b[i, ] <- b[i, ] - a[[i, j]] * b[j, ]
      }
    }
    b[i, ] <- b[i, ] / a[[i, i]]
    det <- det * a[[i, i]]
  }

  list(x=b, det=det)
}

a <- matrix(c(2, 9, 4, 7, 5, 3, 6, 1, 8), 3, 3, byrow=T)
gauss(a, diag(3))


  

You may also check:How to resolve the algorithm String matching step by step in the Wren programming language
You may also check:How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Modula-2 programming language
You may also check:How to resolve the algorithm AKS test for primes step by step in the Fortran programming language
You may also check:How to resolve the algorithm Empty string step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Rep-string step by step in the Bracmat programming language