Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Create FindTheRankOfAMatrix.swift (#5620)
Browse files Browse the repository at this point in the history
Implemented a function that reduces the matrix to its row echelon form and counts the number of pivot elements (non-zero leading elements in each row). The rank of the matrix is equal to the number of these pivot elements.

Co-authored-by: Ritesh Kokam <61982298+RiteshK-611@users.noreply.github.com>
  • Loading branch information
bulutg and RiteshK-611 authored Apr 12, 2024
1 parent a6713d3 commit a0ba7f9
Showing 1 changed file with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import Foundation

func findRankOfMatrix(_ matrix: [[Double]]) -> Int {
var mat = matrix
let rowCount = mat.count
let colCount = mat[0].count
var rank = 0

for row in 0..<colCount {
if row < rowCount {
var swapRow = row
while mat[swapRow][row] == 0 {
swapRow += 1
if swapRow == rowCount {
swapRow = row
break
}
}
mat.swapAt(row, swapRow)

if mat[row][row] != 0 {
for i in (row+1)..<rowCount {
let factor = mat[i][row] / mat[row][row]
for j in row..<colCount {
mat[i][j] -= factor * mat[row][j]
}
}
rank += 1
}
}
}

return rank
}

// Example usage
let matrix = [
[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]
]

let rank = findRankOfMatrix(matrix)
print("Rank of the matrix: \(rank)")

0 comments on commit a0ba7f9

Please sign in to comment.