-1

I wrote some code to insert a value along the diagonal of a matrix, but I can't figure out why it's giving me the error: fatal error: Index out of range

The code:

        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

            }
        }
Hamish
  • 78,605
  • 19
  • 187
  • 280
loltospoon
  • 239
  • 1
  • 9

2 Answers2

0

Index out of range error is thrown when you try to access/write a value out of the arraybounds. In this case you are probably trying to write a value at particleinboxHamil[i][j] for a value i or j bigger than your array bounds.

particleinboxHamil is just an empty array (it is instantiated as such) and thus there is no particleinboxHamil[i][j] to write on.

Simon
  • 2,419
  • 2
  • 18
  • 30
  • Ok, so I need to instantiate...wait, is my notation even correct? I'm trying to make an `NxN` matrix, but I saw that matrices don't really exist in Swift, we only have these multi-dimensional arrays. Am I defining a *matrix* correctly in my code? – loltospoon Apr 12 '17 at 22:01
  • You might want to take a look at the following stackoverflow and/or google somewhat about 2d arrays in swift. Many people before you have conquered the issue you are facing: http://stackoverflow.com/questions/25127700/two-dimensional-array-in-swift – Simon Apr 12 '17 at 22:07
  • @loltospoon Or review the questions and answers used to close your question as a duplicate. – rmaddy Apr 12 '17 at 22:08
0

You are assigning to an empty array. Intialize it first

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???
    }
}
Code Different
  • 90,614
  • 16
  • 144
  • 163