Array{Float64,2} -> Array{Float64,1}

When indexing an Array{Float64,2}

julia> A = ones(1,5)
1×5 Array{Float64,2}:
1.0 1.0 1.0 1.0 1.0

julia> A[1,2:5]
4-element Array{Float64,1}:
1.0
1.0
1.0
1.0

Why am I being given an Array{Float64,1}?

I’m expecting to get:

1×4 Array{Float64,2}:
1.0 1.0 1.0 1.0

A slice of a matrix is a vector, so has size (n,). If you want a 1xn matrix back, you can use A[[1], 2:5], or if you just want it to be a row vector, you can do A[1, 2:5]'

1 Like

Related to this topic of mine.

1 Like

Depending on your preference, you can also use range indexing.

A[1:1, 2: 5]

I prefer this, because it’s consistent to that 2:5 syntax.

3 Likes

Thanks for replying so quickly!
Seems so obvious now I know, thank you

Simple rule: the dimensionality of the output is the summed dimensionality of the indexes. So A[i,j], where i and j are Ints, gives you a scalar (zero-dimensional). You supplied one scalar and one vector, so you got a 1-dimensional output.

The fun doesn’t stop there. Here’s an example that some other languages would struggle with:

julia> v = [10, 20, 30, 40, 50]
5-element Vector{Int64}:
 10
 20
 30
 40
 50

julia> idx = [1 2;
              5 2]
2×2 Matrix{Int64}:
 1  2
 5  2

julia> v[idx]
2×2 Matrix{Int64}:
 10  20
 50  20
3 Likes