Weird behavior with 3-dimensional arrays (beginner)

I am trying to work with 3-dimensions arrays. My understanding is that they are just like matrices but with one extra index (so like a “deck” of matrices).

Sometimes the arrays appear to be behaving as expected but sometimes not. Here is an example where I got completely unexpected results. (It seems like maybe sometimes running the same code multiple times is giving me different results possibly due to how the arrays are stored in memory? I am working in Jupyterlab)

Here is some code I ran which gave me the results in the screenshot below.

I thought when I initialize the arrays, they would just be zero, and then scalar multiplication multiplies each component and array addition is component-wise. That should give a 4 in position [1,1,1], a 4 in position [2,1,1] and zeros elsewhere.

What am I missing? Thanks

x = Array{Float64}(undef, (2,5,7))
# adjust

y = Array{Float64}(undef, (2,5,7))

x[2,1,1] = 7
y[1,1,1] = 4
x
y
2*x + y

1 Like

undef means uninitialized

You want the function zeros to initialize an array of zeros.

4 Likes

To complement this answer, you should change the code above into

x = zeros(2,5,7)
# adjust

y = zeros(2,5,7)
2 Likes