Elementary row operations¶
author: Parin Chaipunya affil: KMUTT
Elementary row operations¶
Recall that there are three types of elementary row operations, namely
- Swap any two rows. (
sw) - Multiply a nonzero scalar to a row. (
sc) - Add or subtract any two rows. (
add)
This notebook will demonstrate how these operations are done with numpy so that we could use it to do calculations with larger matrices.
We begin by importing numpy.
import numpy as np
Swapping rows¶
Suppose that A is a ndarray.
We could swap the rows i1 and i2 by using A[[i1,i2],:] = A[[i2,i1],:].
A = np.array([[1, 1, 1], [2, 2, 2,], [3, 3, 3,]])
print(A)
[[1 1 1] [2 2 2] [3 3 3]]
# Swap rows 1 and 3. (R1 <-> R3)
A[[0, 2], :] = A[[2, 0], :]
print(A)
[[3 3 3] [2 2 2] [1 1 1]]
Multiplying a scalar to a row¶
Suppose that A is a ndarray. We could multiply a scalar a to row i by A[i,:] = a*A[i,:].
The shorthand A[i,:] *= a could also be used (if there is no data type conflicts).
A = np.array([[1, 1, 1], [2, 2, 2,], [3, 3, 3,]])
print(A)
[[1 1 1] [2 2 2] [3 3 3]]
# Multiply -2 to Row 2. (R2 <- -2R2)
A[1, :] *= -2
print(A)
[[ 1 1 1] [-4 -4 -4] [ 3 3 3]]
Adding / subtracting two rows¶
To add or subtract rows i1 and i2 ($R_{i1} \leftarrow R_{i1} \pm R_{i2}$) of an array A, we do A[i1,:] = A[i1,:] + A[i2,:] or A[i1,:] = A[i1,:] - A[i2,:].
The shorthands A[i1,:] += A[i2,:] or A[i1,:] -= A[i2,:] could also be used (if there is no data type conflicts).
A = np.array([[1, 1, 1], [2, 2, 2,], [3, 3, 3,]])
print(A)
[[1 1 1] [2 2 2] [3 3 3]]
# Add row 1 to row 3 (R3 <- R3 + R1).
A[2, :] += A[0, :]
print(A)
[[1 1 1] [2 2 2] [4 4 4]]
# Subtract 2*row 3 from row 2 (R2 <- R2 - 2R3)
A[1, :] -= 2 * A[2, :]
print(A)
[[ 1 1 1] [-6 -6 -6] [ 4 4 4]]
Finding a REF¶
Now that we know how the elementary row operations are performed, we now combine them to find a row echelon form of a matrix.
Example 1¶
Find a REF of the matrix $$ A = \left[ \begin{array}{rrrr} 1 & 2 & 5 & 1 \\ 0 & 0 & 0 & 2 \\ 3 & 1 & 0 & 0 \\ -1 & -2 & -10 & 1 \end{array} \right] $$
A = np.array([[1, 2, 5, 1], [0, 0, 0, 2], [3, 1, 0, 0], [-1, -2, -10, 1]])
print(A)
[[ 1 2 5 1] [ 0 0 0 2] [ 3 1 0 0] [ -1 -2 -10 1]]
# R3 <- R3 - 3R1
# R4 <- R4 + R1
A[2,:] -= 3*A[0,:]
A[3,:] += A[0,:]
print(A)
[[ 1 2 5 1] [ 0 0 0 2] [ 0 -5 -15 -3] [ 0 0 -5 2]]
# R2 <-> R3
A[[1,2],:] = A[[2,1],:]
print(A)
[[ 1 2 5 1] [ 0 -5 -15 -3] [ 0 0 0 2] [ 0 0 -5 2]]
# R3 <-> R4
A[[2,3],:] = A[[3,2],:]
print(A)
[[ 1 2 5 1] [ 0 -5 -15 -3] [ 0 0 -5 2] [ 0 0 0 2]]