Creating Column Matrix with Array Literals

Hi, How we can create a column matrix (i.e. nx1) with array literals? I am aware of other ways for achieving this such as using initializer functions such as “zeros” and “ones”. but how we can do this with array literals? I expect the following snippet create a column matrix:

A = [1; 2]

and also following snippet:

A = [1
     2]

but both of this will create a 1 dimensional array as “2-element Array{Int64,1}”.
in Documetation explicitly states:

Concatenation
If the arguments inside the square brackets are separated by semicolons ( ; ) or newlines >instead of commas, then their contents are vertically concatenated together instead of the >arguments being used as elements themselves.

I think this is a little inconsistency in Julia syntax.

1 Like

No, because 1d arrays are treated as column vectors in all of the Julia linear-algebra routines. (Because of this, it’s not clear why you need to create a 1-column matrix instead of a 1d array?)

You could use reshape([1,2],2,1).

(It might also make sense to have a constructor Matrix(x::Vector) = reshape(x, length(x), 1); currently there is no such constructor defined in Base.)

See also this discussion and issue #17084.

Thank you for your respond. my point is if semicolon or newline concatenate vertically why it does not work in this case?

Because it is doing “vertical” concatentation (vcat) — from Julia’s perspective, a 1d array is “vertical”, and more generally the first dimension of any array (of any dimensionality) is defined to be “vertical”. For the same reason:

julia> [[3,4]; [5,6]]
4-element Array{Int64,1}:
 3
 4
 5
 6

julia> size([rand(3,4,5); rand(17,4,5)])
(20, 4, 5)
1 Like

Thank you. your explanation helped.