user2820579
user2820579

Reputation: 3451

Weird set index error

I am stuck on this chunk of code

hdiag = zeros(Float64,2)
hdiag = [0,0]
println(hdiag)
hdiag[1] = randn()

In the last line I obtain an InexactError. It is strange because randn() it's a Float64, but for some reason I have to do hdiag=randn(2) and then there should not be a problem.

Upvotes: 2

Views: 108

Answers (1)

mbauman
mbauman

Reputation: 31342

The line:

hdiag = [0,0]

changes hdiag to refer to a completely new and different array than what it was before. In this case, that new array is an integer array, and so any subsequent assignments into it need to be convertible to integers.

Indexed assignment is different; it changes the contents of the existing array. So you can use hdiag[:] = [0,0] and it will change the contents, converting the integers to floats as it does so. This gets even easier in version 0.5, where you can use the new .= dot assignment syntax to assign into an existing array:

hdiag .= [0,0]

will do what you want. For more details on arrays, bindings, and assignment, I recommend reading this blog post: Values vs. Bindings: The Map is Not the Territory.

Upvotes: 6

Related Questions