help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
swift-ios-calculator
RSK World
swift-ios-calculator
Swift iOS Calculator v1.0 - AI Math Solver + 3D Graphing + Apple Watch Integration + iOS Widgets + Siri Shortcuts + Currency Converter + Scientific Calculator + Matrix Operations + Platform Integration + Modern iOS Development
swift-ios-calculator
  • Assets.xcassets
  • Base.lproj
  • swift-ios-calculator.xcodeproj
  • AIMathSolverViewController.swift26.6 KB
  • AppDelegate.swift1.7 KB
  • CalculatorHistoryViewController.swift6.5 KB
  • CalculatorLogic.swift4.4 KB
  • CalculatorSettingsViewController.swift5.6 KB
  • CalculatorTheme.swift8.3 KB
  • CalculatorUtils.swift6.9 KB
  • CalculatorViewController.swift3.4 KB
  • CalculatorWidget.swift14.3 KB
  • CalculatorWidgetInfo.plist846 B
  • ChemistryCalculatorViewController.swift26.9 KB
  • CurrencyConverterViewController.swift13.3 KB
  • CustomFormulaBuilderViewController.swift22.1 KB
  • EngineeringCalculatorViewController.swift25.7 KB
  • EquationSolverViewController.swift22.8 KB
  • FinancialCalculatorViewController.swift27.5 KB
  • GeometryCalculatorViewController.swift29.7 KB
  • Graphing3DViewController.swift20.8 KB
  • GraphingCalculatorViewController.swift14.7 KB
  • Info.plist3.2 KB
  • LICENSE1.1 KB
  • MainTabBarController.swift22.3 KB
  • MatrixCalculatorViewController.swift26.6 KB
  • PRIVACY_POLICY.md1.6 KB
  • PhysicsCalculatorService.swift8.2 KB
  • ProgrammerCalculatorViewController.swift11 KB
  • README.md8.7 KB
  • RELEASE_NOTES.md6.5 KB
  • SceneDelegate.swift2.8 KB
  • ScientificCalculatorViewController.swift6.2 KB
  • SiriShortcutsManager.swift23.5 KB
  • Swift iOS Calculator.entitlements1.1 KB
  • UnitConverterViewController.swift14 KB
  • WatchCalculatorViewController.swift15.3 KB
  • index.html47.5 KB
MatrixCalculatorViewController.swift
MatrixCalculatorViewController.swift
Raw Download
Find: Go to:
//
//  MatrixCalculatorViewController.swift
//  Swift iOS Calculator
//
//  Created by RSK World on 23/01/2026.
//  Copyright © 2026 RSK World. All rights reserved.
//
//  Developer: Molla Samser (Founder, RSK World)
//  Designer & Tester: Rima Khatun
//  Contact: info@rskworld.com, +91 93305 39277
//  Website: https://rskworld.in
//  Address: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
//

import UIKit

class MatrixCalculatorViewController: UIViewController {
    
    // MARK: - Outlets
    @IBOutlet weak var matrixASizeSegmentedControl: UISegmentedControl!
    @IBOutlet weak var matrixBSizeSegmentedControl: UISegmentedControl!
    @IBOutlet weak var operationSegmentedControl: UISegmentedControl!
    @IBOutlet weak var matrixACollectionView: UICollectionView!
    @IBOutlet weak var matrixBCollectionView: UICollectionView!
    @IBOutlet weak var resultCollectionView: UICollectionView!
    @IBOutlet weak var calculateButton: UIButton!
    @IBOutlet weak var clearButton: UIButton!
    @IBOutlet weak var swapButton: UIButton!
    @IBOutlet weak var transposeButton: UIButton!
    @IBOutlet weak var determinantButton: UIButton!
    @IBOutlet weak var inverseButton: UIButton!
    @IBOutlet weak var rankButton: UIButton!
    @IBOutlet weak var eigenvaluesButton: UIButton!
    @IBOutlet weak var resultLabel: UILabel!
    
    // MARK: - Properties
    private var matrixA: Matrix = Matrix(rows: 3, columns: 3)
    private var matrixB: Matrix = Matrix(rows: 3, columns: 3)
    private var resultMatrix: Matrix?
    
    private var matrixASize: MatrixSize = .threeByThree
    private var matrixBSize: MatrixSize = .threeByThree
    private var currentOperation: MatrixOperation = .addition
    
    enum MatrixSize: String, CaseIterable {
        case twoByTwo = "2×2"
        case threeByThree = "3×3"
        case fourByFour = "4×4"
        
        var rows: Int {
            switch self {
            case .twoByTwo: return 2
            case .threeByThree: return 3
            case .fourByFour: return 4
            }
        }
        
        var columns: Int {
            return rows
        }
    }
    
    enum MatrixOperation: String, CaseIterable {
        case addition = "A + B"
        case subtraction = "A - B"
        case multiplication = "A × B"
        case scalarMultiplication = "k × A"
        case transpose = "Aᵀ"
        case determinant = "det(A)"
        case inverse = "A⁻¹"
        case rank = "rank(A)"
        case eigenvalues = "λ(A)"
        
        var requiresMatrixB: Bool {
            switch self {
            case .addition, .subtraction, .multiplication:
                return true
            default:
                return false
            }
        }
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupCollectionViews()
        setupSegmentedControls()
        initializeMatrices()
    }
    
    // MARK: - Setup
    private func setupUI() {
        title = "Matrix Calculator"
        view.backgroundColor = CalculatorTheme.shared.backgroundColor
        
        // Setup buttons
        setupButton(calculateButton, title: "Calculate", color: .systemGreen)
        setupButton(clearButton, title: "Clear", color: .systemRed)
        setupButton(swapButton, title: "Swap A↔B", color: .systemBlue)
        setupButton(transposeButton, title: "Transpose", color: .systemOrange)
        setupButton(determinantButton, title: "Determinant", color: .systemPurple)
        setupButton(inverseButton, title: "Inverse", color: .systemTeal)
        setupButton(rankButton, title: "Rank", color: .systemIndigo)
        setupButton(eigenvaluesButton, title: "Eigenvalues", color: .systemPink)
        
        // Setup result label
        resultLabel.backgroundColor = CalculatorTheme.shared.displayBackgroundColor
        resultLabel.textColor = CalculatorTheme.shared.textColor
        resultLabel.layer.cornerRadius = 8
        resultLabel.textAlignment = .center
        resultLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        resultLabel.numberOfLines = 0
    }
    
    private func setupButton(_ button: UIButton, title: String, color: UIColor) {
        button.setTitle(title, for: .normal)
        button.backgroundColor = color
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 8
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .medium)
    }
    
    private func setupCollectionViews() {
        setupCollectionView(matrixACollectionView)
        setupCollectionView(matrixBCollectionView)
        setupCollectionView(resultCollectionView)
        
        matrixACollectionView.tag = 0
        matrixBCollectionView.tag = 1
        resultCollectionView.tag = 2
    }
    
    private func setupCollectionView(_ collectionView: UICollectionView) {
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = CalculatorTheme.shared.backgroundColor
        collectionView.layer.cornerRadius = 8
        collectionView.layer.borderWidth = 2
        collectionView.layer.borderColor = CalculatorTheme.shared.buttonBackgroundColor.cgColor
        
        // Register cell
        collectionView.register(UINib(nibName: "MatrixCell", bundle: nil), forCellWithReuseIdentifier: "MatrixCell")
        
        // Add gesture recognizer for keyboard dismissal
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        collectionView.addGestureRecognizer(tapGesture)
    }
    
    private func setupSegmentedControls() {
        setupSegmentedControl(matrixASizeSegmentedControl, titles: MatrixSize.allCases.map { $0.rawValue })
        setupSegmentedControl(matrixBSizeSegmentedControl, titles: MatrixSize.allCases.map { $0.rawValue })
        setupSegmentedControl(operationSegmentedControl, titles: MatrixOperation.allCases.map { $0.rawValue })
    }
    
    private func setupSegmentedControl(_ segmentedControl: UISegmentedControl, titles: [String]) {
        segmentedControl.removeAllSegments()
        for (index, title) in titles.enumerated() {
            segmentedControl.insertSegment(withTitle: title, at: index, animated: false)
        }
        segmentedControl.selectedSegmentIndex = 1 // Default to 3×3
        segmentedControl.backgroundColor = CalculatorTheme.shared.buttonBackgroundColor
        segmentedControl.selectedSegmentTintColor = CalculatorTheme.shared.accentColor
        segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: CalculatorTheme.shared.textColor], for: .normal)
        segmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .selected)
    }
    
    private func initializeMatrices() {
        matrixA = Matrix(rows: matrixASize.rows, columns: matrixASize.columns)
        matrixB = Matrix(rows: matrixBSize.rows, columns: matrixBSize.columns)
        
        matrixACollectionView.reloadData()
        matrixBCollectionView.reloadData()
    }
    
    // MARK: - Actions
    @IBAction func matrixASizeChanged(_ sender: UISegmentedControl) {
        matrixASize = MatrixSize.allCases[sender.selectedSegmentIndex]
        matrixA = Matrix(rows: matrixASize.rows, columns: matrixASize.columns)
        matrixACollectionView.reloadData()
        clearResult()
    }
    
    @IBAction func matrixBSizeChanged(_ sender: UISegmentedControl) {
        matrixBSize = MatrixSize.allCases[sender.selectedSegmentIndex]
        matrixB = Matrix(rows: matrixBSize.rows, columns: matrixBSize.columns)
        matrixBCollectionView.reloadData()
        clearResult()
    }
    
    @IBAction func operationChanged(_ sender: UISegmentedControl) {
        currentOperation = MatrixOperation.allCases[sender.selectedSegmentIndex]
        updateButtonVisibility()
        clearResult()
    }
    
    @IBAction func calculateButtonPressed(_ sender: UIButton) {
        performOperation()
    }
    
    @IBAction func clearButtonPressed(_ sender: UIButton) {
        clearAll()
    }
    
    @IBAction func swapButtonPressed(_ sender: UIButton) {
        swapMatrices()
    }
    
    @IBAction func transposeButtonPressed(_ sender: UIButton) {
        transposeMatrix()
    }
    
    @IBAction func determinantButtonPressed(_ sender: UIButton) {
        calculateDeterminant()
    }
    
    @IBAction func inverseButtonPressed(_ sender: UIButton) {
        calculateInverse()
    }
    
    @IBAction func rankButtonPressed(_ sender: UIButton) {
        calculateRank()
    }
    
    @IBAction func eigenvaluesButtonPressed(_ sender: UIButton) {
        calculateEigenvalues()
    }
    
    // MARK: - Methods
    private func performOperation() {
        view.endEditing(true)
        
        switch currentOperation {
        case .addition:
            resultMatrix = matrixA + matrixB
            resultLabel.text = "Matrix A + Matrix B"
            
        case .subtraction:
            resultMatrix = matrixA - matrixB
            resultLabel.text = "Matrix A - Matrix B"
            
        case .multiplication:
            if matrixA.columns == matrixB.rows {
                resultMatrix = matrixA * matrixB
                resultLabel.text = "Matrix A × Matrix B"
            } else {
                showAlert(title: "Error", message: "Cannot multiply: A columns must equal B rows")
                return
            }
            
        case .scalarMultiplication:
            let scalar = showScalarInputDialog()
            if let scalar = scalar {
                resultMatrix = matrixA * scalar
                resultLabel.text = "\(scalar) × Matrix A"
            }
            
        case .transpose:
            resultMatrix = matrixA.transpose()
            resultLabel.text = "Transpose of Matrix A"
            
        case .determinant:
            calculateDeterminant()
            return
            
        case .inverse:
            calculateInverse()
            return
            
        case .rank:
            calculateRank()
            return
            
        case .eigenvalues:
            calculateEigenvalues()
            return
        }
        
        if let result = resultMatrix {
            resultCollectionView.reloadData()
            animateResultAppearance()
        }
    }
    
    private func transposeMatrix() {
        resultMatrix = matrixA.transpose()
        resultLabel.text = "Transpose of Matrix A"
        resultCollectionView.reloadData()
        animateResultAppearance()
    }
    
    private func calculateDeterminant() {
        guard matrixA.isSquare else {
            showAlert(title: "Error", message: "Determinant can only be calculated for square matrices")
            return
        }
        
        let det = matrixA.determinant()
        resultLabel.text = "det(A) = \(String(format: "%.4f", det))"
        clearResultMatrix()
    }
    
    private func calculateInverse() {
        guard matrixA.isSquare else {
            showAlert(title: "Error", message: "Inverse can only be calculated for square matrices")
            return
        }
        
        let det = matrixA.determinant()
        if abs(det) < 1e-10 {
            showAlert(title: "Error", message: "Matrix is singular (determinant = 0), cannot calculate inverse")
            return
        }
        
        resultMatrix = matrixA.inverse()
        resultLabel.text = "A⁻¹ (det = \(String(format: "%.4f", det)))"
        resultCollectionView.reloadData()
        animateResultAppearance()
    }
    
    private func calculateRank() {
        let rank = matrixA.rank()
        resultLabel.text = "rank(A) = \(rank)"
        clearResultMatrix()
    }
    
    private func calculateEigenvalues() {
        guard matrixA.isSquare else {
            showAlert(title: "Error", message: "Eigenvalues can only be calculated for square matrices")
            return
        }
        
        let eigenvalues = matrixA.eigenvalues()
        let eigenvalueStrings = eigenvalues.map { String(format: "%.4f", $0) }
        resultLabel.text = "λ(A) = [\(eigenvalueStrings.joined(separator: ", "))]"
        clearResultMatrix()
    }
    
    private func swapMatrices() {
        let temp = matrixA
        matrixA = matrixB
        matrixB = temp
        
        let tempSize = matrixASize
        matrixASize = matrixBSize
        matrixBSize = tempSize
        
        matrixASizeSegmentedControl.selectedSegmentIndex = MatrixSize.allCases.firstIndex(of: matrixASize) ?? 1
        matrixBSizeSegmentedControl.selectedSegmentIndex = MatrixSize.allCases.firstIndex(of: matrixBSize) ?? 1
        
        matrixACollectionView.reloadData()
        matrixBCollectionView.reloadData()
        clearResult()
    }
    
    private func clearAll() {
        matrixA = Matrix(rows: matrixASize.rows, columns: matrixASize.columns)
        matrixB = Matrix(rows: matrixBSize.rows, columns: matrixBSize.columns)
        clearResult()
        matrixACollectionView.reloadData()
        matrixBCollectionView.reloadData()
    }
    
    private func clearResult() {
        resultMatrix = nil
        resultLabel.text = "Result will appear here"
        resultCollectionView.reloadData()
    }
    
    private func clearResultMatrix() {
        resultMatrix = nil
        resultCollectionView.reloadData()
    }
    
    private func updateButtonVisibility() {
        let requiresB = currentOperation.requiresMatrixB
        matrixBCollectionView.isHidden = !requiresB
        matrixBSizeSegmentedControl.isHidden = !requiresB
        swapButton.isHidden = !requiresB
    }
    
    private func showScalarInputDialog() -> Double? {
        let alert = UIAlertController(title: "Scalar Multiplication", message: "Enter scalar value:", preferredStyle: .alert)
        
        var textField: UITextField!
        alert.addTextField { field in
            textField = field
            textField.placeholder = "Enter number"
            textField.keyboardType = .decimalPad
        }
        
        var result: Double?
        let semaphore = DispatchSemaphore(value: 0)
        
        alert.addAction(UIAlertAction(title: "Calculate", style: .default) { _ in
            if let text = textField.text, let value = Double(text) {
                result = value
            }
            semaphore.signal()
        })
        
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
            semaphore.signal()
        })
        
        present(alert, animated: true)
        semaphore.wait()
        
        return result
    }
    
    private func animateResultAppearance() {
        resultCollectionView.alpha = 0
        UIView.animate(withDuration: 0.5) {
            self.resultCollectionView.alpha = 1
        }
    }
    
    @objc private func dismissKeyboard() {
        view.endEditing(true)
    }
    
    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        present(alert, animated: true)
    }
}

// MARK: - UICollectionViewDataSource & UICollectionViewDelegate
extension MatrixCalculatorViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch collectionView.tag {
        case 0: // Matrix A
            return matrixASize.rows * matrixASize.columns
        case 1: // Matrix B
            return matrixBSize.rows * matrixBSize.columns
        case 2: // Result
            guard let result = resultMatrix else { return 0 }
            return result.rows * result.columns
        default:
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MatrixCell", for: indexPath) as! MatrixCell
        
        var value: Double
        var isEditable = false
        
        switch collectionView.tag {
        case 0: // Matrix A
            value = matrixA[indexPath.row / matrixASize.columns, indexPath.row % matrixASize.columns]
            isEditable = true
        case 1: // Matrix B
            value = matrixB[indexPath.row / matrixBSize.columns, indexPath.row % matrixBSize.columns]
            isEditable = true
        case 2: // Result
            if let result = resultMatrix {
                value = result[indexPath.row / result.columns, indexPath.row % result.columns]
            } else {
                value = 0
            }
            isEditable = false
        default:
            value = 0
            isEditable = false
        }
        
        cell.configure(value: value, isEditable: isEditable, delegate: self)
        cell.tag = collectionView.tag
        cell.indexPath = indexPath
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let totalWidth = collectionView.frame.width - 10 // Padding
        let columns: Int
        
        switch collectionView.tag {
        case 0:
            columns = matrixASize.columns
        case 1:
            columns = matrixBSize.columns
        case 2:
            columns = resultMatrix?.columns ?? 1
        default:
            columns = 1
        }
        
        let cellWidth = (totalWidth / CGFloat(columns)) - 5
        return CGSize(width: cellWidth, height: cellWidth)
    }
}

// MARK: - MatrixCellDelegate
extension MatrixCalculatorViewController: MatrixCellDelegate {
    
    func matrixCell(_ cell: MatrixCell, valueChanged: Double) {
        guard let indexPath = cell.indexPath else { return }
        
        switch cell.tag {
        case 0: // Matrix A
            matrixA[indexPath.row / matrixASize.columns, indexPath.row % matrixASize.columns] = valueChanged
        case 1: // Matrix B
            matrixB[indexPath.row / matrixBSize.columns, indexPath.row % matrixBSize.columns] = valueChanged
        default:
            break
        }
        
        clearResult()
    }
}

// MARK: - Matrix Class
class Matrix {
    let rows: Int
    let columns: Int
    private var data: [[Double]]
    
    var isSquare: Bool { return rows == columns }
    
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        self.data = Array(repeating: Array(repeating: 0.0, count: columns), count: rows)
    }
    
    init(rows: Int, columns: Int, data: [[Double]]) {
        self.rows = rows
        self.columns = columns
        self.data = data
    }
    
    subscript(row: Int, column: Int) -> Double {
        get {
            precondition(row >= 0 && row < rows && column >= 0 && column < columns, "Index out of bounds")
            return data[row][column]
        }
        set {
            precondition(row >= 0 && row < rows && column >= 0 && column < columns, "Index out of bounds")
            data[row][column] = newValue
        }
    }
    
    // MARK: - Matrix Operations
    static func + (lhs: Matrix, rhs: Matrix) -> Matrix {
        precondition(lhs.rows == rhs.rows && lhs.columns == rhs.columns, "Matrices must have same dimensions")
        
        let result = Matrix(rows: lhs.rows, columns: lhs.columns)
        for i in 0..<lhs.rows {
            for j in 0..<lhs.columns {
                result[i, j] = lhs[i, j] + rhs[i, j]
            }
        }
        return result
    }
    
    static func - (lhs: Matrix, rhs: Matrix) -> Matrix {
        precondition(lhs.rows == rhs.rows && lhs.columns == rhs.columns, "Matrices must have same dimensions")
        
        let result = Matrix(rows: lhs.rows, columns: lhs.columns)
        for i in 0..<lhs.rows {
            for j in 0..<lhs.columns {
                result[i, j] = lhs[i, j] - rhs[i, j]
            }
        }
        return result
    }
    
    static func * (lhs: Matrix, rhs: Matrix) -> Matrix {
        precondition(lhs.columns == rhs.rows, "A columns must equal B rows")
        
        let result = Matrix(rows: lhs.rows, columns: rhs.columns)
        for i in 0..<lhs.rows {
            for j in 0..<rhs.columns {
                var sum = 0.0
                for k in 0..<lhs.columns {
                    sum += lhs[i, k] * rhs[k, j]
                }
                result[i, j] = sum
            }
        }
        return result
    }
    
    static func * (lhs: Matrix, scalar: Double) -> Matrix {
        let result = Matrix(rows: lhs.rows, columns: lhs.columns)
        for i in 0..<lhs.rows {
            for j in 0..<lhs.columns {
                result[i, j] = lhs[i, j] * scalar
            }
        }
        return result
    }
    
    // MARK: - Matrix Methods
    func transpose() -> Matrix {
        let result = Matrix(rows: columns, columns: rows)
        for i in 0..<rows {
            for j in 0..<columns {
                result[j, i] = self[i, j]
            }
        }
        return result
    }
    
    func determinant() -> Double {
        precondition(isSquare, "Matrix must be square")
        
        if rows == 1 {
            return data[0][0]
        } else if rows == 2 {
            return data[0][0] * data[1][1] - data[0][1] * data[1][0]
        } else {
            // Laplace expansion for larger matrices
            var det = 0.0
            for j in 0..<columns {
                det += ((-1.0) ** Double(j)) * data[0][j] * minorMatrix(0, j).determinant()
            }
            return det
        }
    }
    
    func inverse() -> Matrix {
        precondition(isSquare, "Matrix must be square")
        
        let det = determinant()
        precondition(abs(det) > 1e-10, "Matrix is singular")
        
        if rows == 1 {
            return Matrix(rows: 1, columns: 1, data: [[1.0 / data[0][0]]])
        }
        
        let adjugate = adjugateMatrix()
        return adjugate * (1.0 / det)
    }
    
    func rank() -> Int {
        // Simplified rank calculation using Gaussian elimination
        var working = data
        var rank = 0
        
        for col in 0..<columns {
            var pivotRow = -1
            for row in rank..<rows {
                if abs(working[row][col]) > 1e-10 {
                    pivotRow = row
                    break
                }
            }
            
            if pivotRow == -1 { continue }
            
            // Swap rows
            working.swapAt(rank, pivotRow)
            
            // Eliminate column
            for row in (rank + 1)..<rows {
                let factor = working[row][col] / working[rank][col]
                for c in col..<columns {
                    working[row][c] -= factor * working[rank][c]
                }
            }
            
            rank += 1
            if rank == rows { break }
        }
        
        return rank
    }
    
    func eigenvalues() -> [Double] {
        // Simplified eigenvalue calculation for 2x2 matrices
        precondition(isSquare, "Matrix must be square")
        
        if rows == 1 {
            return [data[0][0]]
        } else if rows == 2 {
            let a = data[0][0]
            let b = data[0][1]
            let c = data[1][0]
            let d = data[1][1]
            
            let trace = a + d
            let det = a * d - b * c
            
            let discriminant = trace * trace - 4 * det
            if discriminant < 0 {
                return [] // Complex eigenvalues not supported
            }
            
            let sqrtDiscriminant = sqrt(discriminant)
            return [(trace + sqrtDiscriminant) / 2, (trace - sqrtDiscriminant) / 2]
        } else {
            // For larger matrices, return empty array (would require more complex algorithms)
            return []
        }
    }
    
    // MARK: - Helper Methods
    private func minorMatrix(_ row: Int, _ column: Int) -> Matrix {
        let result = Matrix(rows: rows - 1, columns: columns - 1)
        var resultRow = 0
        
        for i in 0..<rows {
            if i == row { continue }
            var resultCol = 0
            for j in 0..<columns {
                if j == column { continue }
                result[resultRow, resultCol] = self[i, j]
                resultCol += 1
            }
            resultRow += 1
        }
        
        return result
    }
    
    private func adjugateMatrix() -> Matrix {
        let result = Matrix(rows: rows, columns: columns)
        
        for i in 0..<rows {
            for j in 0..<columns {
                let minor = minorMatrix(i, j)
                let cofactor = ((-1.0) ** Double(i + j)) * minor.determinant()
                result[j, i] = cofactor // Transpose for adjugate
            }
        }
        
        return result
    }
}

// MARK: - Supporting Protocols and Classes
protocol MatrixCellDelegate: AnyObject {
    func matrixCell(_ cell: MatrixCell, valueChanged: Double)
}

class MatrixCell: UICollectionViewCell {
    
    @IBOutlet weak var textField: UITextField!
    
    weak var delegate: MatrixCellDelegate?
    var indexPath: IndexPath?
    
    func configure(value: Double, isEditable: Bool, delegate: MatrixCellDelegate?) {
        self.delegate = delegate
        
        textField.text = String(format: "%.2f", value)
        textField.isEnabled = isEditable
        textField.backgroundColor = isEditable ? CalculatorTheme.shared.displayBackgroundColor : UIColor.systemGray5
        textField.textColor = CalculatorTheme.shared.textColor
        textField.textAlignment = .center
        textField.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        textField.layer.cornerRadius = 4
        textField.layer.borderWidth = 1
        textField.layer.borderColor = CalculatorTheme.shared.buttonBackgroundColor.cgColor
        
        // Add target for value changes
        textField.addTarget(self, action: #selector(textFieldChanged), for: .editingChanged)
    }
    
    @objc private func textFieldChanged() {
        guard let text = textField.text, let value = Double(text) else { return }
        delegate?.matrixCell(self, valueChanged: value)
    }
}
773 lines•26.6 KB
swift

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer