rank ()
public
Returns the rank of the matrix. Beware that
using Float values can yield erroneous results
because of their lack of precision. Consider using exact types like Rational or BigDecimal instead.
Matrix [[ 7 , 6 ], [ 3 , 9 ]]. rank
=> 2
Show source # File lib/matrix.rb, line 1272
def rank
# We currently use Bareiss' multistep integer-preserving gaussian elimination
# (see comments on determinant)
a = to_a
last_column = column_count - 1
last_row = row_count - 1
pivot_row = 0
previous_pivot = 1
0.upto(last_column) do |k|
switch_row = (pivot_row .. last_row).find {|row|
a[row][k] != 0
}
if switch_row
a[switch_row], a[pivot_row] = a[pivot_row], a[switch_row] unless pivot_row == switch_row
pivot = a[pivot_row][k]
(pivot_row+1).upto(last_row) do |i|
ai = a[i]
(k+1).upto(last_column) do |j|
ai[j] = (pivot * ai[j] - ai[k] * a[pivot_row][j]) / previous_pivot
end
end
pivot_row += 1
previous_pivot = pivot
end
end
pivot_row
end