Indexing into Matrix

Is there a github issue or discourse post that discusses why

A[1,:]

returns a column vector instead of a row vector (Adjoint) for a matrix A?

From the pattern

A[[1],:] return a 1xn matrix

A[:,[1]] return a nx1 matrix

A[:,1] return a column vector

I was expecting A[1,:] to return a row vector.

Both A[1, :] and A[:, 1] are Vectors. There is no difference between column vectors and row vectors.

This generalizes to multidimensional arrays, where all indices but one are scalars (e.g. A[1, 2, :, 4] returns a Vector). So, it seems strange treating the specific situation A[i, :] any differently (in case you think it should return a Transpose, for example).

If you want a more in-depth explanation, this is related to an old post of mine.

2 Likes

What you refer to as a row vector is known in Julia as a Matrix or a 2D Array with only one row, so if you want that definition, use the A[1:1,:] notation.

julia> A = rand(3,3)
3×3 Array{Float64,2}:
 0.0979413  0.491558   0.134096
 0.991139   0.0406479  0.441085
 0.382994   0.419503   0.272454

julia> A[1:1,:]
1×3 Array{Float64,2}:
 0.0979413  0.491558  0.134096

It may be that issue 4774 and the JuliaCon talk “Taking vector transposes seriously” may give some historical context and useful links.

2 Likes

To be more specific. One of the outcomes of the 4774 issue was the need to have true row vectors (now called Adjoint in Julia) that are different from 1xn matrices to have e.g. inner products a'*b return scalars. Since julia has these “true” row vectors and indexing like A[:,1] returns a column vector (instead of a nx1 matrix) I was wondering if this could work

julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> A[1,:]
1×2 LinearAlgebra.Adjoint{Int64,Array{Int64,1}}:
 1  2

I see your point about multidimensional arrays as Array in base julia has no concept of up or down indices. i.e. a distinction between tensors A^{ij}_{kl} and A^{ijk}_l so there is no way to tell whether A[1,2,:,4] should return a row or column vector but for the 2D case the convention A^i_j seems useful.

Thanks for the link. That post is indeed closely related.