Easy way to merge a vector into a matrix

If I have a matrix and a separate column vector, what is the easiest way to merge that column into the matrix? Typically at the front, but potentially at an arbitrary position?

This is what I came up with. I had to do trial and error with adjoints more than seems desirable but it did work. Is there a simpler way? And what if I wanted the new column to go in the interior of the matrix rather than at the front?

data = rand(4,2)
X = vcat(ones(4)', data')'

Not sure what that transpose is coming up red here. It didn’t do that in Jupyter-- guess its just syntax highlighting getting confused

Here’s one way:

julia> let data = rand(4, 3), v = ones(4)
           [v data]
       end
4×4 Matrix{Float64}:
 1.0  0.0234619  0.965384  0.129006
 1.0  0.0234731  0.208507  0.793128
 1.0  0.637218   0.789261  0.306283
 1.0  0.629813   0.235462  0.924623

Here’s it stuck in the middle:

julia> let data = rand(4, 3), v = ones(4)
           [view(data, :, 1) v view(data, :, 2:3)]
       end
4×4 Matrix{Float64}:
 0.912429   1.0  0.0394902  0.888962
 0.578466   1.0  0.530733   0.152062
 0.0668675  1.0  0.265886   0.752755
 0.943337   1.0  0.962361   0.594233

Now for treating it as a row:

julia> let data = rand(4, 3), v = ones(1, 3)
           [v; data]
       end
5×3 Matrix{Float64}:
 1.0        1.0        1.0
 0.238316   0.845964   0.92684
 0.0655255  0.218186   0.467829
 0.925502   0.86406    0.418347
 0.606538   0.0259459  0.568094

julia> let data = rand(4, 3), v = ones(1, 3)
           [view(data, 1:2, :); v; view(data, 3:4, :)]
       end
5×3 Matrix{Float64}:
 0.149653  0.308625   0.0899298
 0.36977   0.664685   0.289565
 1.0       1.0        1.0
 0.984703  0.0198997  0.942119
 0.856835  0.632953   0.902631

In version 1.7, there’ll even be nict syntax to do this with N dimensional arrays: Syntax for multidimensional arrays by BioTurboNick · Pull Request #33697 · JuliaLang/julia · GitHub

3 Likes

Oh, I should also mention, this is equivalent to hcat:

julia> let data = rand(4, 3)
           vcat(ones(4)', data')' == hcat(ones(4), data)
       end
true
2 Likes