快速矩阵求和

标签 swift matrix sum

我正在尝试开发一个函数,如果它们等于相同的维度,它允许对两个矩阵求和,但我在尝试时收到错误“EXC_BAD_INSTRUCTION”。

这是我的 Playground :

import Foundation

enum RisedError: ErrorType {
    case DimensionNotEquals
    case Obvious(String)
}

func ==(lhs: Matrix, rhs: Matrix) -> Bool {
    return (lhs.rows) == (rhs.rows) && (lhs.columns) == (rhs.columns)
}

protocol Operation {
    mutating func sumWith(matrixB: Matrix) throws -> Matrix
}

struct Matrix {
    let rows: Int, columns: Int
    var grid: [Double]
    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(count: rows * columns, repeatedValue: 0.0)
    }
    func indexIsValidForRow(row: Int, column: Int) -> Bool {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }
    subscript(row: Int, column: Int) -> Double {
        get {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            return grid[(row * columns) + column]
        }
        set {
            assert(indexIsValidForRow(row, column: column), "Index out of range")
            grid[(row * columns) + column] = newValue
        }
    }
}

var matrixA = Matrix(rows: 2, columns: 2)
matrixA[0,0] = 1.0
matrixA[0,1] = 2.0
matrixA[1,0] = 3.0
matrixA[1,1] = 4.0
var matrixB = Matrix(rows: 2, columns: 2)
matrixB[0,0] = 5.0
matrixB[0,1] = 6.0
matrixB[1,0] = 7.0
matrixB[1,1] = 8.0

print(matrixA)
print(matrixB)

extension Matrix: Operation {

    mutating func sumWith(matrixB: Matrix) throws -> Matrix {

        guard self == matrixB else { throw RisedError.DimensionNotEquals }

        for row in 0...self.rows {
            for column in 0...self.columns {
                self[row, column] = matrixB[row, column] + self[row, column]
            }
        }
        return self
    }
}

do {
    try matrixA.sumWith(matrixB)
} catch RisedError.DimensionNotEquals {
    print("The two matrix's dimensions aren't equals")
} catch {
    print("Something very bad happens")
}

错误日志如下:

enter image description here

最佳答案

实际上你的错误是Index out of range

用此代码替换您的扩展程序。

extension Matrix: Operation {

    mutating func sumWith(matrixB: Matrix) throws -> Matrix {

        guard self == matrixB else { throw RisedError.DimensionNotEquals }

        for row in 0...self.rows - 1 {
            for column in 0...self.columns - 1 {
                self[row, column] = matrixB[row, column] + self[row, column]
            }
         }
        return self
    }
}

希望它能解决您的问题。

关于快速矩阵求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37745743/

相关文章:

swift - 序列化 JSON 数据时的空对象

c++ - 返回矩阵 A 中不同行数的最快方法是什么?

java - Java中如何用一个循环来实现两个矩阵相乘?

php - 选择按天分组的列值总和

ios - 当应用程序进入后台时如何保持 Swift Socket IO 运行?

ios - 如何使用 URL 打开应用程序?

mysql - 查找MySQL中两个表的行数差异

excel - 用逗号总结格式化单元格的公式

ios - 日期时间的 AFNetworking URL 参数编码 + 和 : sign

python - 在同一个图上一起绘制两个距离矩阵?