Problem is taken from A First Course in Linear Algebra, Chapter VS - Vector Spaces, Section B - Bases.

A:

Generate the matrix 4 rows and 5 columns and apply row reduced echelon form to discover the pivot columns.

\(\left[\begin{array}{cc}1 & 1 & 1 & 1 & 3 \\3 & 2 & 1 & 2 & 4 \\2 & 1 & 0 & 2 & 1 \\1 & 1 & 1 & 1 & 3\end{array}\right]\)

Once matrix is in row reduced echelon form it should look similar to, \(\left[\begin{array}{cc}1 \\ 0 \\ 0 \\ 0\end{array}\right]\) This would be first pivot column, similarly second pivot column should be, \(\left[\begin{array}{cc}0 \\ 1 \\ 0 \\ 0\end{array}\right]\)

library(stringr)

a = matrix(c(1,3,2,1, 1,2,1,1, 1,1,0,1, 1,2,2,1, 3,4,1,3), nrow=4, ncol=5)

#check if a[1,1] equal zero move it following row
for (i in 1:nrow(a)){
  if (a[1,1] == 0){
    if (i+1 <= nrow(a)){
      swap = a[i+1,]
      a[i+1,] = a[1,]
      a[1,] = swap
      if (a[1,1] != 0){
        break
      }        
    }
  }
}

for (j in 1:nrow(a)){
  k = j+1
  if (k <= nrow(a)){
    for (i in k:nrow(a)){
      swap1 = a[j,j] * a[i,]
      swap2 = a[i,j] * a[j,]
      a[i,] = swap1 - swap2
    }
  }
}

for (j in 2:ncol(a)){
  if (a[1,j] != 0){
    if (a[2,j] != 0){
      swap1 = a[1,]
      swap2 = (a[2,] * a[1,j]) / a[2,j]
      a[1,] = swap1 - swap2
      if (a[1,j] == 0){
        if (a[2,j] < 0){
          a[2,] = -1 * a[2,]
        }
        break
      }
    }
  }
}

for (j in 3:ncol(a)){
  if (a[2,j] != 0){
    if (a[3,j] != 0){
      swap1 = a[2,]
      swap2 = (a[3,] * a[2,j]) / a[3,j]
      a[2,] = swap1 - swap2
      if (a[2,j] == 0){
        if (a[3,j] < 0){
          a[3,] = -1 * a[3,]
        }
        break
      }
    }
  }
}

print(a)
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    0   -1    0   -2
## [2,]    0    1    2    0    5
## [3,]    0    0    0    1    0
## [4,]    0    0    0    0    0

From the above matrix, it can seen first, second and fourth columns are pivot columns. It can programatically identified using below code.

p = rep(0, ncol(a))
for (l in 1:ncol(a)){
  swap = a[,l]
  for (m in 1:nrow(a)){
    f = m -1
    b = nrow(a) - m
    one = "1"
    if (m < 4){
      one = "1,"
    }
    prow = c(paste(paste(replicate(f, "0,"), collapse = ","), paste(replicate(1, one), collapse = ","), paste(replicate(b, "0"), collapse = ","), collapse = ""))
    prow = str_replace_all(prow, ",,", ",")
    prow = as.numeric(unlist(strsplit(prow, split=",")))
    if (all(swap==prow)){
      p[l] = 1
    }
  }
}

p
## [1] 1 1 0 1 0

Following vectors form the basis of S.

\(\{\left[\begin{array}{cc}1 \\3 \\2 \\1 \end{array}\right], \left[\begin{array}{cc}1 \\2 \\1 \\1 \end{array}\right], \left[\begin{array}{cc}1 \\2 \\2 \\1 \end{array}\right]\}\)