Confusing Results When Comparing Arrays in Julia

Hi,

I’m using Julia version 1.10.5 (2024-08-27) on Ubuntu 22.04. I’ve been experimenting with comparing arrays, but I’m getting some confusing results. Here’s my code:

u = [1;2;3]
v = [1 2 3]
A = [1 2 3; 4 5 6]
print(A[1,:])
print(A[1,:] == u)
print(A[1,:] == v)

The output:

3-element Vector{Int64}:
 1
 2
 3

1×3 Matrix{Int64}:
 1  2  3

2×3 Matrix{Int64}:
 1  2  3
 4  5  6

[1, 2, 3]
true
false

I’m puzzled by the fact that print(A[1, :] == u) returns true, while print(A[1, :] == v) returns false. To my understanding, A[1, :] should be a row vector, and the output seems to confirm this.

Can anyone explain why this happens?

Many thanks!

I find it unintuitive, but what’s going on is

julia> A[1,:]
3-element Vector{Int64}:
 1
 2
 3

is a column vector and

julia> A[1:1, :]
1×3 Matrix{Int64}:
 1  2  3

is the row vector.

1 Like

Vector doesn’t inherently distinguish row vs column vectors, you need Matrix for that. Arrays are column-major so Vectors tend to be treated as column vectors, like in array literal syntax ([1,2,3] == [1;2;3]) and linear algebra (A*u works but A*v errors). You’re just seeing the difference between the repr(...) used by print and the repr("text/plain", ...) used by the REPL. Display is actually more complicated than that (show, display, println, etc) but that’s the short version.

julia> [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

julia> repr([1, 2, 3])
"[1, 2, 3]"

julia> repr("text/plain", [1, 2, 3])
"3-element Vector{Int64}:\n 1\n 2\n 3"
1 Like

This behaviour is documented:

If all the indices are scalars, then the result X is a single element from the array A. Otherwise, X is an array with the same number of dimensions as the sum of the dimensionalities of all the indices.
Single- and multi-dimensional Arrays · The Julia Language

That is, if you index with a scalar, its dimensionality is zero. So A[1, :] has dimension 1. That is, it is a Vector{Int} which is an alias for Array{Int, 1}. Now, u is also a Vector{Int}, whereas v is a Matrix{Int} (which is an alias for Array{Int, 2}).

There is no concept of row or column vectors in julia. There are arrays of various sizes. The one-dimensional array is called a Vector, the two-dimensional is called a Matrix. In many linear algebra settings, a Vector is treated as a n x 1 matrix, or a column vector. So that e.g. collect(transpose(u)) is a 1 x 3 matrix.

2 Likes

Hi Benny, thank you!

Hi sgaure, thank you!