Search code examples
matrixindexingjulia

Julia matrix row becomes a column during indexing


Issue: When building a matrix out of single rows, Julia interprets them as columns instead.

julia> a = [1 2 3; 4 5 6; 7 8 9]
3×3 Matrix{Int64}:
 1  2  3
 4  5  6
 7  8  9

julia> b = [a[1:2,:]; a[1:2,:]]
4×3 Matrix{Int64}:
 1  2  3
 4  5  6
 1  2  3
 4  5  6

julia> c = [a[1,:]; a[1,:]]
6-element Vector{Int64}:
 1
 2
 3
 1
 2
 3

How to fix this?


Solution

  • In addition to the range index, you can transpose vectors

    julia> [a[1, :]'; a[1, :]']
    2×3 Array{Int64,2}:
     1  2  3
     1  2  3
    

    It looks likes this approach is somewhat more performant, than the range index, but it should be tested on larger matrices, also it is not consistent, if you have ranges and single columns

    using BenchmarkTools
    
    f1(a) = [a[1:1,:]; a[1:1,:]]
    f2(a) = [a[1, :]'; a[1, :]']
    
    julia> @btime f1($a)
      122.440 ns (3 allocations: 352 bytes)
    2×3 Array{Int64,2}:
     1  2  3
     1  2  3
    
    julia> @btime f2($a)
      107.480 ns (3 allocations: 352 bytes)
    2×3 Array{Int64,2}:
     1  2  3
     1  2  3