在Swift中将值插入矩阵

时间:2017-04-12 21:48:27

标签: arrays swift matrix

我写了一些代码来沿矩阵的对角线插入一个值,但我无法弄清楚为什么它会给我错误:fatal error: Index out of range

代码:

        var tempHamil = [[Double]]()
        var particleinboxHamil = [[Double]]()
        let boxlength: Double = LengthOfBox

        for i in 0...NumberEigenvalues-1{
            for j in 0...NumberEigenvalues-1{

                if i==j {

                    particleinboxHamil[i][j] = particleinboxenergy(ValueForN: i, LengthOfBox: box length)//error is thrown here

                } else {

                    particleinboxHamil[i][j]=0.0

                }

                tempHamil = particleinboxHamil

            }
        }

2 个答案:

答案 0 :(得分:0)

当您尝试从数组块中访问/写入值时,将引发索引超出范围错误。在这种情况下,您可能尝试在particleinboxHamil[i][j]处写入一个值i或j大于数组边界的值。

particleinboxHamil只是一个空数组(它被实例化),因此没有particleinboxHamil[i][j]可以写入。

答案 1 :(得分:0)

您正在分配一个空数组。首先初始化

let emptyRow = [Double](repeating: 0.0, count: NumberEigenvalues)
var tempHamil = [[Double]](repeating: emptyRow, count: NumberEigenvalues)
var particleinboxHamil = tempHamil
let boxlength: Double = LengthOfBox

for i in 0..<NumberEigenvalues {
    for j in 0..<NumberEigenvalues {

        if i == j {
            particleinboxHamil[i][j] = particleinboxenergy(ValueForN: i, LengthOfBox: box length)//error is thrown here

        }

        tempHamil = particleinboxHamil  // what's this for???
    }
}