rank()
public
Returns the rank of the matrix. Beware
that using Float values, with their usual lack of
precision, can affect the value returned by this method. Use Rational values instead if this is important to
you.
Matrix[[7,6], [3,9]].rank
=> 2
Show source
def rank
if column_size > row_size
a = transpose.to_a
a_column_size = row_size
a_row_size = column_size
else
a = to_a
a_column_size = column_size
a_row_size = row_size
end
rank = 0
k = 0
begin
if (akk = a[k][k]) == 0
i = k
exists = true
begin
if (i += 1) > a_column_size - 1
exists = false
break
end
end while a[i][k] == 0
if exists
a[i], a[k] = a[k], a[i]
akk = a[k][k]
else
i = k
exists = true
begin
if (i += 1) > a_row_size - 1
exists = false
break
end
end while a[k][i] == 0
if exists
k.upto(a_column_size - 1) do
|j|
a[j][k], a[j][i] = a[j][i], a[j][k]
end
akk = a[k][k]
else
next
end
end
end
(k + 1).upto(a_row_size - 1) do
|i|
q = a[i][k] / akk
(k + 1).upto(a_column_size - 1) do
|j|
a[i][j] -= a[k][j] * q
end
end
rank += 1
end while (k += 1) <= a_column_size - 1
return rank
end